在Publisher上执行副作用 [英] Performing side effects on Publisher
问题描述
我正在尝试在 Publisher
上执行副作用,但找不到任何允许我执行类似操作的运算符.确切地说,我正在寻找与RxSwift的 do(on:)
类似的概念.
I'm trying to perform side effect on Publisher
, and I can't find any operator which will allow me to do something like this. To be precise, I'm looking for a concept similar to RxSwift's do(on:)
.
这就是我想要做的.我正在为第三方SDK提供的委托编写反应式包装.它是用于与BLE设备进行交互的SDK.我有 startScanning
和 stopScanning
之类的方法,而我想要实现的是对信号做出反应并调用 stopScanning
作为任何错误或副作用的副作用.完成事件.到目前为止,我有这样的事情:
Here's what I'm trying to do.
I'm writing a reactive wrapper for a delegate provided by a 3rd party SDK. It's and SDK for interacting with BLE devices. I have methods like startScanning
and stopScanning
and what I want to achieve is to react to signals and call stopScanning
as a side effect of any error or complete events. So far, I have something like this:
newDeviceFoundPublisher
.timeout(.seconds(timeout), scheduler: DispatchQueue.global())
.eraseToAnyPublisher()
我想要实现的是这样的:
and what I want to achieve is something like:
newDeviceFoundPublisher
.timeout(.seconds(timeout), scheduler: DispatchQueue.global())
.doOnError {
manager.stopScanning()
}
.doOnComplete {
manager.stopScanning()
}
.eraseToAnyPublisher()
是否已经有类似的东西,或者我丢失了某些东西,并且在Combine中有一些东西我可以使用并获得结果?
Is there already something like this or maybe I'm missing something, and there's something in Combine I can use and get the result?
推荐答案
您可能正在寻找 .handleEvents
运算符.您可以使用五个不同参数中的任何一个来实现它.它们都是可选的,因此仅实现您需要的那些.错误和完成都将计为 receiveCompletion:
.
You might be looking for the .handleEvents
operator. You can implement it with any of five different parameters; they are all optional, so implement just those you need. Both an error and a completion would count as receiveCompletion:
.
请注意,如果您不 catch
,该错误仍将继续沿流水线传播!(无论如何,完成都会顺着管道进行,我认为您不能停止它.)
Note that the error will still flow on down the pipeline if you don't catch
it! (The completion will flow down the pipeline in any case, and I don't think you can stop it.)
这篇关于在Publisher上执行副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!