0

I have two Signals from Notifications. These where fired from an external framework.

let successSignal = NotificationCenter.default.reactive.notifications(forName: NSNotification.Name(rawValue: "someNotification"))
let failedSignal = NotificationCenter.default.reactive.notifications(forName: NSNotification.Name(rawValue: "someNotification"))

Now I want to combine them to one signal of type Signal<Notification, Error>. If successSignal fires send Value, if failedSinal fires send Error.

I have no idea how to manage this.

SWIE
  • 76
  • 4

1 Answers1

0

Here's a way to do this:

enum SignalErrors: Error {
    case failedSignalValue
}

let failingFailed = failedSignal.flatMap(FlattenStrategy.latest) { _ in
    return SignalProducer<Int, SignalErrors>(error: SignalErrors.failedSignalValue)
}

For this new signal, a value on the failedSignal will be turned into an error Event, so failingFailed is a Signal on which events on failedSignal now arrive as .failed instead of .value.

Keep the Event Stream Grammar in mind - after one .failed event, the Signal terminates!

let merged = Signal.merge([
    successSignal
        .promoteError(SignalErrors.self),
    failingFailed
])

Then we merge the successSignal and failingFailed signal together. Since a .failed event behaves like an exception and propagates immediately, the whole merged signal will also fail immediately when a .failed event arrives on failingFailed.

The promoteError on successSignal is necessary for type checking reasons.

MeXx
  • 3,357
  • 24
  • 39