gpt4 book ai didi

swift 结合。如何转变出版商值(value)观

转载 作者:行者123 更新时间:2023-12-04 04:24:05 27 4
gpt4 key购买 nike

我需要使用后端提供的链接下载文件。要下载文件,使用返回 Progress() 对象的异步 API。问题是 FlatMap 无法从 Publisher<[Link], Error> 映射至 Publisher<[File], Error> .我要解决的另一个问题是一旦 Progress.fractionCompleted 等于 1.0,就摆脱可取消并以某种方式转换 Progress 信息文件路径。

现在我尝试使用 map功能。请参阅 Playground 中的代码:

import UIKit
import Combine

var progress = Progress()
extension ProgressUserInfoKey {
public static var destinationURL = ProgressUserInfoKey("destinationURL")
}

func download(from urlRequest: URLRequest, to destinationURL: URL) -> AnyPublisher<Progress, Error> {
return Future<Progress, Error> { promise in
progress = Progress(totalUnitCount: 1)
progress.setUserInfoObject(destinationURL.absoluteString,
forKey: ProgressUserInfoKey.destinationURL)
promise(.success(progress))
// Simulate async API
DispatchQueue.main.async {
progress.completedUnitCount = 1
}
}.eraseToAnyPublisher()
}

struct Link: Decodable {
let url: String
}

func getLinks() -> AnyPublisher<[Link], Error> {
return URLSession.shared.dataTaskPublisher(for: URL(string: "https://backend.com")!)
.map { $0.data }
.decode(type: [Link].self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}

struct File {
let url: URL
let size: UInt32
}

private func destinationUrl(_ fromUrl: String?) -> URL {
guard let path = fromUrl else {
return URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
}
return URL(fileURLWithPath: path)
}

/// 2) How to get rid of this state and transoft Progress into filePath directly (using matp(transform: ? )
var cancellableSet = Set<AnyCancellable>()

func getFiles() -> AnyPublisher<[File], Error> {
getLinks()
.flatMap { (links) -> AnyPublisher<[File], Error> in
let sequence = Sequence<[AnyPublisher<File, Error>], Error>(sequence: links.map {
download(from: URLRequest(url: $0), to: destinationUrl(UUID().uuidString))
.sink { progress in
progress.publisher(for: \.fractionCompleted).sink { progressValue in
if progressValue == 1.0 {
let filePath: String = progress.userInfo[ProgressUserInfoKey.destinationURL] as? String ?? ""
/// 1) How to return publisher here
///return Publisher(File(url: URL(string: filePath)!, size: 0))
}
}
.store(in: &cancellableSet)
}
.store(in: &cancellableSet)
} )
return sequence.flatMap { $0 }.collect().eraseToAnyPublisher()
}
}

我期待代码编译成功并且函数 getFiles返回 AnyPublisher<[File], Error> .

目前得到的错误代码如下:

Cannot convert return expression of type 'Publishers.FlatMap<AnyPublisher<[File], Error>, AnyPublisher<[Link], Error>>' to return type 'AnyPublisher<[File], Error>'

最佳答案

问题已通过使用 Publishers.Sequence() 扩展并避免调用函数 sink() 得到解决。我还使用 flatMap() 来转换输出值。可以在此处找到以这种方式演示的代码:Combine publishers together

关于 swift 结合。如何转变出版商值(value)观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58251867/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com