Performing side effects on Publisher

為{幸葍}努か 提交于 2020-07-04 03:27:04

问题


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:).

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()

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?


回答1:


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:.

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.)



来源:https://stackoverflow.com/questions/62139342/performing-side-effects-on-publisher

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!