Observables are useful when we want to manage and/or combine multiple events over time.
Lets imagine we have a method will return a promise for that JSON:
const dataPromise = fetchData('https://jsonplaceholder.typicode.com/posts');
Also, imagine that we're tracking user presence on the current page:
const userLeavePromise = trackUserPresence();
Lets now draw timelines for the data fetching and user leaving events. Here o
stands for event, happening in time:
1s 2s 3s 4s 5s
data ------------o
userLeave --------o
For example sake, data would be fetched at 4th second, while our restless user would leave the page at 3rd. In this case we want to cancel the fetch operation and all post-processing callbacks (in Promise terms, all .then
-ned functions).
For such (and many more) situations RxJS provides lots of operators that let us combine events over time.
In this particular case we would take data, Until user leaves the page:
// Observable for data
const data$ = fetchData('https://jsonplaceholder.typicode.com/posts');
// Observable for user leave
const userLeave$ = trackUserPresence();
data$
.takeUntil(userLeave$)
.subscribe(data => console.log(data))