Home > Software engineering >  Why does Observer in ReactiveSwift have send method?
Why does Observer in ReactiveSwift have send method?

Time:01-02

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)

CodePudding user response:

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:

  • In the context of observing a signal, the signal is sending events to the observer i.e. the observer is "observing" the signal.
  • In the context of pipe, your code is sending events to the observer i.e. the observer is "observing" your code.

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.

  • Related