How do I throw an error on a behaviour subject and continue the stream?

前端 未结 3 1843
长发绾君心
长发绾君心 2020-12-09 14:55

On one end, I have a stream which may occasionally throw an error:

this.behaviorSubject.error(error)

Later on, however, I want to continue

3条回答
  •  臣服心动
    2020-12-09 15:29

    This may not work for your situation, but I ran into this same issue when work with Angular 2 because we would navigate across screens and would want the service to retry an API and not just call the error function again. It would actually cause bigger issues because the function was called in our constructor and the error function would try to update the UI which was not yet ready.

    What I did seems to work fine and be pretty clean. I created a reset the Subject in the error handler.

    subject.subscribe( 
       ( value ) =>  {  /* ok */ },
       ( error ) =>  {  
          //handle error
          //reset subject
          this.subject = new Subject();
       }
    );
    

    This works in our case because every time you navigate to the screen new subscriptions are getting torn down from the old screen then set up in the new, so the new subject won't hurt anything.

提交回复
热议问题