swiftreactive-programmingreactive-swift

Why does Observer in ReactiveSwift have send method?


I feel confused when I see the sample code from ReactiveSwift, because intuitively observer is expected to receive events. Why does Observer is designed to have send(_:) method?

// Signal.pipe is a way to manually control a signal. 
// the returned observer can be used to send values to the signal
let (signal, observer) = Signal<Int, Never>.pipe()
observer.send(value: 10)

Solution

  • I agree this is a bit confusing in the context of pipe, in which the "observer" is generally thought of as an input, whereas the term "observer" makes you think about observing the output of a signal.

    The way I think about it is that in both cases something is being observed, even if those things are very different:

    Hopefully that explains why the same type is used in both situations. Note that you can use the observer returned from pipe() to observe a signal directly:

    let someSignal: Signal<Int, Never> = ...
    
    let (signal, observer) = Signal<Int, Never>.pipe()
    
    someSignal.observe(observer)
    

    This code "pipes" the events from someSignal to signal via observer.