softshipper
softshipper

Reputation: 34081

What happen with further clicks

I have an observable that will throw an error, when the counter will be reach 5:

let counter = 0;

const source2 = Rx.Observable.of(true)
    .map(() => [1,2,3,4,5]);

source2
    .subscribe((x) => console.log(x),
               (err) => console.log(err),
               () => console.log("complete 2!!"));


const source1 = Rx.Observable.fromEvent(document, 'click')
    .do(() => console.log("Document clicked!"))
    .do(() => counter++)
    .map(() => {

      if(counter > 5) {
        counter = 0;
        throw new Error("Counter is too big!");
      }

      return true;

    })
    .catch((oError, oSource$) => source2)


source1
    .subscribe((x) => console.log(x),
               (err) => console.log(err),
               () => console.log("complete!!"));

When the error got threw, then it will switch to source2 as you can see on the code above.

When I make further clicks on the document, nothing will happen why? What happen with further clicks?

Upvotes: 0

Views: 35

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16892

This is one of the basic rxjs-paradigms: Whenever an error is thrown in a stream (no matter if it is a direct throw new Error(..) or Observable.throw(...)) the subscribed stream is automatically finalized and subscribers are unsubscribed.

So the behavior is expected.

To fix this in your personal case: Don't throw an error if you don't want your stream to stop and unless you want to resubscribe manually.

Addition: The catch-operator just allows for reacting to an error within the stream, independently from any subscriber - the stream itself will still be finalized though - the name catch kind of gives a false impression here. - You can "retry" the observable by returning the original source in the catch-operator, which will effectively create a new stream based on that source, the old stream, however, will still be finalized.

Upvotes: 1

Related Questions