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

前端 未结 3 1832
长发绾君心
长发绾君心 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:36

    Short answer: It's not possible.

    How to work with this: The basic concept of RxJS is that any error or complete-call will basically "kill" a stream. This concept forces you not "just to throw around errors here and there as you please" but to handle errors and the flow of data within your application properly. A BehaviorSubject for example is typically meant to hold data, however it should not be used to also include the process of retrieving/creating that data and handle possible errors that might occur during the retrieval of the data.

    So if you want to go by the book, you should split up your flow into two parts:

    1. Retrieval/creation of the data: A stream, that will run once then then completes and/or throws an error whenever one occurs. When the data is retrieved it will be sent to the store.
    2. The store (e.g. as in your case: a bunch of BehaviorSubjects): Only valid data arrives in the store, this means that no error-handling is done here and all parts relying on the store can trust in the store that it holds the correct data.

    As an example your data flow could look as follows (as a rough sketch):

    store.ts

    dataStore: BehaviorSubject = new BehaviorSubject();
    errorMessage: BehaviorSubject = new BehaviorSubject();
    

    data-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);
    }
    

    "But this looks like a lot of overhead..." - True, however it ensures a clean and easy-to-understand flow of data within your application, that is easy to test and maintain. Also there are ready-to-use store-concepts like ngrx or redux that could be used.

提交回复
热议问题