softshipper
softshipper

Reputation: 34099

Why hot observable resubscribe

I have an observable that listen on table select event, it is also hot.

The code snippet:

  const oTableRowSelect$ = TableOb.rowSelectionChangeEvent$(this.getById("ins-table"));
  const test = oTableRowSelect$
    .do(function () {
      console.log("resubscribe");
    })
    .map(function () {
      return 4;
    });

  test.subscribe(function (o) {
    console.log("Select1" + o);
  });

  test.subscribe(function (o) {
    console.log("Select2" + o)
  });

As you can see, there are two subscribers, that listen on the event. So the result should share to all subscribers, that what is called a replay effect.

The output, that I've got is: enter image description here

But I am expecting resubscribe output only once. What am I doing wrong?

Upvotes: 1

Views: 86

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16892

While your oTableRowSelect$ might be hot and shared, it is only shared up the the part where you extend it somehow with additional operator(s) (in your case do and map).

In RxJS any extension through an operator will basically return a "new" stream. In order to make this "new" stream hot/shared you'd have to apply an operator that makes it hot (share, publish, publishReplay, ect...)

const hotBaseStream$ = new Rx.BehaviorSubject("Hi!");

const test = hotBaseStream$
    // -------- below this line you get a "new" stream, that is not hot any more
    .do(() => console.log("resubscribe"))
    .map(() => 4)
    .publishReplay().refCount();  // remove this part and you will have back your original behavior

  test.subscribe(function (o) {
    console.log("Select1 ", o);
  });

  test.subscribe(function (o) {
    console.log("Select2 ", o)
  });
<script src="https://unpkg.com/@reactivex/rxjs/dist/global/Rx.js"></script>

Upvotes: 1

Related Questions