我正在发现Combine.我编写了以组合"方式发出HTTP请求的方法,例如:
I am discovering Combine. I wrote methods that make HTTP requests in a "combine" way, for example:
func testRawDataTaskPublisher(for url: URL) -> AnyPublisher<Data, Error> { var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 15) request.httpMethod = "GET" return urlSession.dataTaskPublisher(for: request) .tryMap { return $0.data } .eraseToAnyPublisher() }我想多次调用该方法并完成一个任务,例如:
I would like to call the method multiple times and do a task after all, for example:
let myURLs: [URL] = ... for url in myURLs { let cancellable = testRawDataTaskPublisher(for: url) .sink(receiveCompletion: { _ in }) { data in // save the data... } }上面的代码不起作用,因为我必须将cancellable存储在属于该类的变量中.第一个问题是:将许多(例如1000个)可取消对象存储在 Set< AnyCancellable> 之类的东西中是个好主意吗???会不会导致内存泄漏?
The code above won't work because I have to store the cancellable in a variable that belongs to the class. The first question is: is it a good idea to store many (for example 1000) cancellables in something like Set<AnyCancellable>??? Won't it cause memory leaks?
var cancellables = Set<AnyCancellable>() ... let cancellable = ... cancellables.insert(cancellable) // ???第二个问题是:所有可取消条件完成后如何启动任务?我在想类似的东西
And the second question is: how to start a task when all the cancellables are finished? I was thinking about something like that
class Test { var cancellables = Set<AnyCancellable>() func run() { // show a loader let cancellable = runDownloads() .receive(on: RunLoop.main) .sink(receiveCompletion: { _ in }) { _ in // hide the loader } cancellables.insert(cancellable) } func runDownloads() -> AnyPublisher<Bool, Error> { let myURLs: [URL] = ... return Future<Bool, Error> { promise in let numberOfURLs = myURLS.count var numberOfFinishedTasks = 0 for url in myURLs { let cancellable = testRawDataTaskPublisher(for: url) .sink(receiveCompletion: { _ in }) { data in // save the data... numberOfFinishedTasks += 1 if numberOfFinishedTasks >= numberOfURLs { promise(.success(true)) } } cancellables.insert(cancellable) } }.eraseToAnyPublisher() } func testRawDataTaskPublisher(for url: URL) -> AnyPublisher<Data, Error> { ... } }通常我会使用 DispatchGroup ,启动多个HTTP任务,并在任务完成时使用通知,但是我想知道如何使用Combine以现代的方式编写代码.
Normally I would use DispatchGroup, start multiple HTTP tasks and consume the notification when the tasks are finished, but I am wondering how to write that in a modern way using Combine.
推荐答案通过创建发布者集合,应用 flatMap 运算符,然后 collect ,以等待所有发布者完成后再继续.这是您可以在游乐场中运行的示例:
You can run some operations in parallel by creating a collection of publishers, applying the flatMap operator and then collect to wait for all of the publishers to complete before continuing. Here's an example that you can run in a playground:
import Combine import Foundation func delayedPublisher<Value>(_ value: Value, delay after: Double) -> AnyPublisher<Value, Never> { let p = PassthroughSubject<Value, Never>() DispatchQueue.main.asyncAfter(deadline: .now() + after) { p.send(value) p.send(completion: .finished) } return p.eraseToAnyPublisher() } let myPublishers = [1,2,3] .map{ delayedPublisher($0, delay: 1 / Double($0)).print("\($0)").eraseToAnyPublisher() } let cancel = myPublishers .publisher .flatMap { $0 } .collect() .sink { result in print("result:", result) }以下是输出:
1: receive subscription: (PassthroughSubject) 1: request unlimited 2: receive subscription: (PassthroughSubject) 2: request unlimited 3: receive subscription: (PassthroughSubject) 3: request unlimited 3: receive value: (3) 3: receive finished 2: receive value: (2) 2: receive finished 1: receive value: (1) 1: receive finished result: [3, 2, 1]请注意,所有发布者都将立即开始(以其原始顺序).
Notice that the publishers are all immediately started (in their original order).
1/$ 0 延迟会导致第一个发布者花费最长的时间来完成.请注意最后的值顺序.由于第一个完成时间最长,因此它是最后一个.
The 1 / $0 delay causes the first publisher to take the longest to complete. Notice the order of the values at the end. Since the first took the longest to complete, it is the last item.
更多推荐
Apple Combine框架:如何并行执行多个发布者并等待所有发布者完成?
发布评论