Search code examples
javascriptangularrxjsbehaviorsubject

Update spesific element in behaviorsubject, or only subscribe once


Im having an BehaviorSubject that is getting continues updates every 5 secs from my other files.

But, somethimes i cant wait 5 sec for the new event to occur, so im looking for a way to update only one single element of the Behaviorsubject.

i have created the following to handle the single element:

 updateSingleTimer(timer,time,secs = false) {
    this.timers$.pipe(takeUntil(this._destroyed$)).subscribe((data:any) => {
      var newdata = data;
      newdata[timer] = time;
      this.updateTimers(newdata);
    });
  }

of course, this will create an infinity loop, cause timers is updated once updateTimers function is called.

So, i need to only get the timers data in updateSingleTimer function once, and not subscribe to it.

Q: How would i change the code above so it will only get result once from this.timers$?

Q: also, is it possible to update one single element an easier way than what im doing currently?

full code:

  _timers = new BehaviorSubject<any>(null);
  private timersChangeSet = new Subject<any>();
  constructor(private http: HttpClient, private router: Router) {
    this.timersChangeSet.subscribe(val => this._timers.next(val))
}

  timers$ = this._timers.asObservable();

updateTimers(object) {
    this.timersChangeSet.next(object);
  }


  updateSingleTimer(timer,time,secs = false) {

// the code will result in infinity loop, of course. but how would i only get the value once?
    this.timers$.pipe(takeUntil(this._destroyed$)).subscribe((data:any) => {
      var newdata = data;
      newdata[timer] = time;
      this.updateTimers(newdata);
    });
  }

Solution

  • Just take 1

    this.timers$.pipe(take(1), takeUntil(this._destroyed$))