简体   繁体   中英

Stop next execution of Rxjs observer?

I am trying with the basic use case of a Rxjs observer. This is what I am doing:

const { Observable } = require('rxjs');

Observable.create(o => { 
  setTimeout(() => o.next('hi'), 1000); 
  setTimeout(() => { throw new Error('A mistake') }, 1500); 
  setTimeout(() => o.next('this should not print'), 2000) }
).subscribe({
  next: x => console.log(x),
  error: y => console.log('error', y),
  complete: () => console.log('done')
});

The out put of this is the following:

> hi
Error: A mistake
    at Timeout.setTimeout [as _onTimeout] (repl:1:89)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)
> this should not print

What I need to do is stop the execution of the next, and even If I unsubscribe my subscription it is not stopping the next execution.

I tried like this too:

let subscription;

let source = Observable.create(o => { 
  try {
    setTimeout(() => o.next('hi'), 1000); 
    setTimeout(() => { throw new Error('A mistake') }, 1500); 
    setTimeout(() => o.next('this should not print'), 2000) 
  } catch (e) {
    subscription.unsubscribe();
    return 'error';
  }
});
subscription = source.subscribe({
  next: x => console.log(x),
  error: y => console.log('error', y),
  complete: () => console.log('done')
});

but no chance... it did not stop.

What I have as code is not just set timeout I have async and await code like this:

let subscription;

let source = Observable.create(async o => { 
  try {
    o.next(await anEvent()); 
    o.next(await anEventThatThrowsAnException()); 
    o.next(await anEventThatIWantToAvoidDueToTheException()); 
  } catch (e) {
    subscription.unsubscribe();
    return 'error';
  }
});
subscription = source.subscribe({
  next: x => console.log(x),
  error: y => console.log('error', y),
  complete: () => console.log('done')
});

How can I achieve this code to stop the "this should not print" ?

After you set the timer with setTimeout , you will not prevent it's execution with unsubscribe .

You will need to manually clear your timeouts.

Note that you can save your timeouts in variables var myTimeout = setTimeout(f,ms); then you can cancel then clearTimeout(myTimeout);

Read More:

This is the way to make it work with observer.error as stated by ABOS. In fact this is his example and it works.

So Just for documentation purposes I answered this question with his answer from the comment.

ABOS answer

I just thought that if someone is having problem trying to handle errors throwing the error instead of catching and executing observer.error in the way that is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM