我试图用.receive(on: DispatchQueue.main)
切换到下游的主线程,但是当使用.subscribe(:)
或.sink(receiveValue:)
时,我没有收到输入。如果我不改变线程,我会收到正确的输入。
出版商
extension URLSessionWebSocketTask {
struct ReceivePublisher: Publisher {
typealias Output = Message
typealias Failure = Error
let task: URLSessionWebSocketTask
func receive<S>(subscriber: S) where S: Subscriber, Output == S.Input, Failure == S.Failure {
task.receive { result in
switch result {
case .success(let message): _ = subscriber.receive(message)
case .failure(let error): subscriber.receive(completion: .failure(error))
}
}
}
}
}
extension URLSessionWebSocketTask {
func receivePublisher() -> ReceivePublisher {
ReceivePublisher(task: self)
}
}
用户
extension ViewModel: Subscriber {
typealias Input = URLSessionWebSocketTask.Message
typealias Failure = Error
func receive(subscription: Subscription) {}
func receive(_ input: URLSessionWebSocketTask.Message) -> Subscribers.Demand {
// Handle input here.
// When using `.receive(on:)` this method is not called when should be.
return .unlimited
}
func receive(completion: Subscribers.Completion<Error>) {}
}
订阅
socketTask.receivePublisher()
.receive(on: DispatchQueue.main)
.subscribe(viewModel)
socketTask.resume()
最佳答案
AnyCancellable
返回的subscribe<S>(_ subject: S) -> AnyCancellable
在被取消初始化时将调用cancel()
因此,如果不保存它,当调用块超出范围时,它将被取消初始化。
在我从WWDC看到的视频和教程中,如何处理这个问题从未提到过。我所看到的是,人们正在向RxSwift的DisposeBag
解决方案漂移。
更新Beta 4:
Combine现在提供了一个名为:AnyCancellable
的方法,它与我以前的解决方案差不多。您可以将store(in:)
存储在一组AnyCancellable
中:
var cancellables = Set<AnyCancellable>()
...
override func viewDidLoad() {
super.viewDidLoad()
...
socketTask.receivePublisher()
.receive(on: DispatchQueue.main)
.subscribe(viewModel)
.store(in: &cancellables)
}
这样,当包含类被取消初始化时,数组(以及所有
AnyCancellable
s)将被取消初始化。过时的:
如果您希望所有
AnyCancellable
s的解决方案都能以更好的方式使用,您可以这样扩展Cancellable
:extension Cancellable {
func cancel(with cancellables: inout [AnyCancellable]) {
if let cancellable = self as? AnyCancellable {
cancellables.append(cancellable)
} else {
cancellables.append(AnyCancellable(self))
}
}
}
关于ios - 使用`.receive(on:DispatchQueue.main)`时不接收输入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56677669/