ReactiveCocoa 4: How to send error to an observer

2019-07-18 06:30发布

问题:

let (signal, sink) = Signal<[CLBeacon], BeaconManagerError>.pipe()

When I call this because the user disabled the Bluetooth:

sendError(self.sink, error)

the Signal is interrupted and I don't receive more next nor interrupted events after enabling the Bluetooth back again. The Signal is broken.

How can I send error types to the observer without interrupting / breaking the Signal? I can't find in the RAC 4 documentation. Thanks!

回答1:

By design, an error causes the signal to finish. The documentation says:

failures should only be used to represent “abnormal” termination. If it is important to let operators (or consumers) finish their work, a Next event describing the result might be more appropriate.

If you want to turn errors into Next events, you can use flatMapError operator as described here or use retry if you want to allow only several occurances of the error.



回答2:

If you want different semantics than Next* (Error|Completed) I recommend encoding that in the type. You can use a Signal that can't fail, but which values can be either success or failure, by using Result:

Signal<Result<[CLBeacon], BeaconManagerError>, NoError>

That signal will emit no errors, but its Next events will be Result.Success<[CLBeacon]> or Result.Failure<BeaconManagerError>, **and the signal won't terminate when receiving a Result.Failure.