How to share the same data between multiple subscribers

How to share the same data between multiple subscribers

How to share data between multiple subscribers

Live example here

Have you ever wanted to share a particular data with multiple subscribers?

Thanks to rxjs built in operators it's pretty simple to do it. Just add the share() operator and let rxjs to handle the rest.

##Example: First, we need to make an observable that will emit 6 values. To do so, we have to use interval and take operator.

let a = interval(1000).pipe(take(6));

##Let’s make a simple example of how share() operator works:

1.Without the share() operator:

let a = interval(1000).pipe(take(7));

a.subscribe(appendToInnerHTML(withoutShareOperator));

setTimeout(() => {
  a.subscribe(appendToInnerHTML(withoutShareOperator));
}, 1000);

In order to see the differences, we have to use two subscribers. First observer will subscribe and then after at least 1 second our next observer will also subscribe. The output will be something like this: `01021324354656` Marble diagram should look like the following:

0--1--2--3--4--5--6
---0--1--2--3--4--5--6

2.With share() operator

a = a.pipe(share());

a.subscribe(appendToInnerHTML(withShareOperator));

setTimeout(() => {
  a.subscribe(appendToInnerHTML(withShareOperator));
}, 3000);

Here we've introduced the `share()` operator. Our emitted values will look something like this: `01233445566`

Also, the marble diagram should be like the following:
--1--2--3--4--5--6
--------3--4--5--6

Conclusion:

When you what to get the data shared across 2 streams and you need only the data that is left, you need to use share(); Stay close and you will learn how to share data already pushed when the new clients will subscribe. Se you in the next article!

Share This: