Search code examples
angularbehaviorsubject

BehaivorSubject return null


I have this problem, I need the behaivorSubject not to return the value when it is null, since the result is grabbed by a component made by third parties and if this is null it throws me an error.

It should return the same only when I get the response from the server, I leave my code here:

  getCarList(params): Observable<CarListGrid> {
    if (this.carListSubject$ === undefined) {
      this.carListSubject$ = new BehaviorSubject<CarListGrid>(null);
      this.refetchCarList(params);
    }
    return this.carListSubject$.asObservable();
  }

  refetchCarList(gridParams) {
    const subscription = this.http.post<CarListGrid>(this.baseUrl + 'GetCar', {gridParams} ,httpOptions).pipe(map(data => this.setDefaultValuesToCar(data))).subscribe(
      (response) => {

        this.carListSubject$.next(response);
        subscription.unsubscribe();
      });
  }

Is there any way to prevent the subject from responding with a value when it is null? Or else, how can I give this code another way to help me with that?

Thanks!


Solution

  • You could filter those nulls out, like this:

    getCarList(params): Observable<CarListGrid> {
      if (this.carListSubject$ === undefined) {
        this.carListSubject$ = new BehaviorSubject<CarListGrid>(null);
        this.refetchCarList(params);
      }
      return this.carListSubject$
        .asObservable()
        .pipe(filter((value) => value !== null));
    }