How can I make a mistake for the behavior object and continue the flow?

At one end, I have a thread that can sometimes cause an error:

this.behaviorSubject.error(error)

Later, however, I want to continue the flow:

this.behaviorSubject.next(anotherValue)

on the other end, I have a subscriber subscribed to behaviorSubject.asObservable().

In the subscription, I handle the value and the error:

.subscribe( 
   ( value ) =>  {  /* ok */ },
   ( error ) =>  {  /* some error */ }
);

I want the effect to be the same as a simple callback onSuccessand onErrorwhere it onErroris called every time an error occurs and does not interfere with future calls onSuccess. How to do it with RXJS?

I was looking for a trick, but it looks like it just prevents calling callers.

+14
source share
3 answers

: .

: RxJS , error complete -call "" . " , ", . A BehaviorSubject, , , , / , .

, , :

  • / : , , / , . , .
  • (, : BehaviorSubjects): , , , , , .

( ):

store.ts

dataStore: BehaviorSubject<IData> = new BehaviorSubject<IData>();
errorMessage: BehaviorSubject<IErrorMsg> = new BehaviorSubject<IErrorMsg>();

-retrieval.ts

fetchDataById(id: string) {
    httpService.get(`some/rest/endpoint/${id}`)
        .subscribe(handleData, handleError);
}

handleData(data: IData) {
    errorMessage.next(null);
    dataStore.next(data);
}

handleError(error: Error) {
    errorMessage.next(error.message);
    dataStore.next(null);
}

" ". , , , . -, ngrx redux, .

+9

Rx , , (onComplete onError). Observable , Observable. .catch , - .

Rx.Observable.interval(500)
  .mergeMap(i => i % 3 == 2 ? Rx.Observable.throw(new Error('kboom')) : Rx.Observable.of(i))
  .catch(err => Rx.Observable.of(err.message))
  .subscribe(
    val => console.log('val: ' + val),
    err => console.log('err: ' + err),
    () => console.log('stream completed')
  )

, 5

this.behaviorSubject.error(error), , . - , :

this.behaviorSubject.next({ value: 'somevalue' });
this.behaviorSubject.next({ error: error });
this.behaviorSubject.next({ value: 'somevalue' });

, .

+3

, Angular 2, , API, . , , , .

, , , . reset Subject .

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

, , , , , .

0

Source: https://habr.com/ru/post/1679341/


All Articles