我訂閱了組合發布者,但經常在.sink
. 有沒有更方便的方法來做到這一點?
import _Concurrency
import Combine
import Foundation
import PlaygroundSupport
var cancellable = Set<AnyCancellable>()
struct MyService {
private static let subject = PassthroughSubject<String, Never>()
init() {
Task {
try? await Task.sleep(until: .now .seconds(2), clock: .suspending)
Self.subject.send("Publisher: " Date.now.formatted())
}
}
func publisher() -> AnyPublisher<String, Never> {
Self.subject.eraseToAnyPublisher()
}
}
class MyClass {
let service: MyService
var cancellable: AnyCancellable?
init() {
service = MyService()
subscribe()
}
func subscribe() {
// HERE ===>
cancellable = service.publisher()
.sink { value in Task { [weak self] in await self?.doThings(value: value) } }
}
func doThings(value: String) async {
print(value)
try? await Task.sleep(until: .now .seconds(2), clock: .suspending)
print("Things done!")
}
}
let test = MyClass()
PlaygroundPage.current.needsIndefiniteExecution = true
我想做的是無縫呼叫并發任務,.sink
例如:
// From:
service.publisher()
.sink { value in Task { [weak self] in await self?.doThings(value: value) }
// To:
service.publisher()
.sink { [weak self] value in await self?.doThings(value: value) }
uj5u.com熱心網友回復:
你可以這樣寫一個擴展:
extension Publisher where Failure == Never {
func sinkAsync(receiveValue: @escaping ((Self.Output) async throws -> Void)) -> AnyCancellable {
sink { value in
Task {
try await receiveValue(value)
}
}
}
}
請注意,它采用的閉包是async throws
,這與 的閉包所Task.init
具有的相同。
我認為這樣做的“本機”方式是將發布者轉換為異步序列。
Task {
for await value in service.publisher().values {
await self.doThings(value: value)
}
}
請注意,通過這樣做,您不需要管理可取消的!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/512858.html
標籤:迅速结合快速并发
上一篇:有沒有辦法在重繪后將照片永久保存到Xcode應用程式?
下一篇:如何從IntentTimelineProvider背景關系中讀取widgetRenderingMode和其他environmentVariants