What is it?
Real world
Think of it as a network of water pipes.
- You have a source, our water tank
- Then a series of pipes and connectors
- which may divert flows to various rooms
- or change the water into something else
Participants
- An Observable (water tank) emits items
- An optional Transformation (water connector?) transforms items into
- A consumer is a doer which can act on those items
- A Subscriber consumes those items
- Observables don’t start emitting items until someone explicitly subscribes to them
Coding example
// We want to print the words in UPPERCASE // Observable Observable<String> observable = Observable.just("how", "to", "do", "in", "java"); // Consumer Consumer<? super String> consumer = System.out::println; observable // Transformation using map() method .map(w -> w.toUpperCase()) // Subscriber .subscribe(consumer);
Communication flow
- Connect the subscriber to consumer using
subscribe()
- As soon as, we connect both,
- events start flowing
- subscriber start act on events by consumer
- Internally, when event is emitted from the observable,
- the
onNext()
method is called on each subscriber onComplete()
or theonError()
method is called on the subscriber when the observable finishes all of events
- the
Leave a Reply