Java.Reactive.Describe the role of Observable and Observer in reactive programming

🎯 Goal of Reactive Programming:

To react to a stream of data/events over time, in a non-blocking, asynchronous, and declarative way.

This is achieved by two main players:


🧩 1. Observable<T> — The Data Source

✅ What it is:

An Observable is like a publisher or data stream. It emits:

  • Data (onNext)
  • Errors (onError)
  • Completion (onComplete)

You can think of it as a “smart pipe”:

  • You push data into it.
  • It knows how to process and send that data to whoever is listening.

🔧 Common ways to create an Observable:

Observable.just("A", "B", "C")  // Emits 3 items
Observable.fromIterable(list)   // Emits items from a list
Observable.create(...)          // Custom emission logic

🧩 2. Observer<T> — The Listener

✅ What it is:

An Observer is like a subscriber. It listens to the Observable, and reacts to:

  • New data (onNext(T t))
  • Errors (onError(Throwable e))
  • Completion (onComplete())

It’s like saying: “Hey, I’m interested in your updates — keep me posted!”

🔧 Example:

Observable<String> stream = Observable.just("A", "B", "C");

stream.subscribe(
    item -> System.out.println("Got: " + item),        // onNext
    error -> System.err.println("Error: " + error),    // onError
    () -> System.out.println("Completed")              // onComplete
);

📦 Together, they form a reactive flow:

[ Observable ] ──▶ onNext("A") ──▶ [ Observer ]
                ──▶ onNext("B")
                ──▶ onComplete()

Think of:

  • Observable = a stream of events
  • Observer = someone watching those events happen, and reacting

🧠 Real-world analogy:

ConceptAnalogy
ObservableA radio station broadcasting music
ObserverA radio listener tuned in

Once the station starts playing (emitting), everyone tuned in hears the songs (data), and if there’s a problem (error), the station may announce it or stop (complete).

🛠 Lifecycle Methods in Observer:

interface Observer<T> {
    void onSubscribe(Disposable d);  // (Optional) - when you subscribe
    void onNext(T value);            // When new data is emitted
    void onError(Throwable e);       // If something goes wrong
    void onComplete();               // When the stream finishes
}

But often, we just use the short subscribe(...) with lambdas.

🌀 Bonus: Hot vs Cold Observables

  • Cold: Starts emitting when someone subscribes (e.g. Observable.just()).
  • Hot: Already emitting whether you’re listening or not (e.g. mouse events).
This entry was posted in Без рубрики. Bookmark the permalink.