this post is still work in progress it will be updated often in the future, trying to quickly clarify some ‘reactive thinking’ to Java devs

Why I have to unsubscribe?

The subscriptions can survive the components that created them. This could create a memory leak in the application.

When I don’t need to unsubscribe?

Are Observables eager or lazy?

Lazy. Observables starts only when an observer subscribe (e.g. .subscribe()).

Promises are eager.

Are Observables synchronous or asynchronous

They can be synchronous or asynchrounous.

Promises are only asynch.

How many values are returned?

From 0 to potentially infinite values.

When my Subscriber will start to receive values?

After the subscription when the Observable will emit the next value or, in case of BehaviorSubject immediately (previous or initial value).

What is the difference between Subject, BehaviorSubject, ReplaySubject?

How to combine 2 streams, e.g. 2 database tables by key

This case is very frequent if you are working with databases and you have to combine two streams representing a database by key. The best option you have is combineLatest :

personWithAddress$ = combineLatest(
  this.personList$,
  this.adressList$)
)

this would emit an array containing the two arrays: [PersonList[], Adresses[]] this value can be passed through your rxjs pipe.

Observables can manage multiple observers?

When to unsubscribe

There are multiple strategies:

  1. ngOnDestroy and Array

A very common solution is to unsubscribe when the component is destroyed. A common practice is to store all the Subscriptions in an array and unsubscribe them in a loop forEach.

private subscriptions: Subscription[] = [];

ngOnInit() {
  this.subscriptions.push(this.yourObservables.subscribe())
}

ngOnDestroy() {
  this.subscriptions.forEach(subscription => subscription.unsubscribe());
}
  1. Subject and takeUntil

example

Some useful operators