See also the pattern description on Wikipedia
If you're already familiar with the concept as how it is realised in RxJS, go read next section about it.
Observables allow you to push messages from your publishers to your subscribers in a way where publishers do not have to care for what subscriber they post messages to and subscribers don't have to know where and what the publisher is. That's because publishers, subscribers and connection between them are three different things. Let's see the example of it:
import { Observable } from '@hullo/core';// first - create a subject with some publisherconst answersToAll = new Observable(observer => {// observer represents future subscriber// let's send it a simple messageobserver.next(42);});// second - there is a subscriberconst subscriber = {next: message => {// do sth with the received message},complete: () => {// do sth when publisher decided// to not push any more messages}};// third - connect subscriber to the subjectconst subscription = answersToAll.subscribe(subscriber);// (bonus) you can stop receiving messages// externally to both publisher and subscriber// through subscription objectsubscription.cancel();
You'll find yourself writing second step and the third next to themselves, usually as one step. So there will be two steps, but those are still three separate concepts. First step might be even more than often in a completely separate file and for a reason!
The separation is a key to understand usefulness of this pattern. Due to a standard interface of Observer
there is no need for the publisher to know where and why the subscription starts as the only responsibility of that is to emit specific to it messages. You can find similar concepts made with EventEmitter both on web and in Node.
In Node you can have ReadableStream
that is a specific emitter which by itself doesn't know about what is reading the stream other than that it has to provide functions that'll be run on specific events.
In the browsers JS, any DOM node can be an emitter of events and then it just awaits for the developer to submit a function that should express a reaction to a click, a keystroke etc. Event emission can be done with Observable
s as well and in respective Hullo packages, there are helper function to get around in these environments.