Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
RXJS ANGULAR - Observable still called after takeWhile operator is resolved

I am storing data in the session storage with an expiry date :

private saveSessionData<T>(key: string, value: T) {
    const item = {
      value: value,
      expiry: Date.now() + 10 * 60000 // 10 minutes from now
    }
    sessionStorage.setItem(key, JSON.stringify(item));
  }

I have an other function to access those data, that will return null if the data I try to access is expired :

private async getSessionData<T>(key: string): Promise<T | null> {
    const itemStr = sessionStorage.getItem(key);
    const item = JSON.parse(itemStr);
    if (Date.now() > item.expiry) {
      console.log('CONSOLE NULL');
      await this.alertService('OBJ EXPIRED');
      return null;
    }
    return item.value;
  }

I access those data like that :

getMyObj$ (): Observable<MyObj| null> {
    return from(this.getSessionData<MyObj>(this._myObj))
      .pipe(
        takeWhile(myObj => myObj != null),
        tap(x => console.log('getting my Obj')
    );
  }

In my View, I'm using the | async to show myObj with a two way data binding :

<div *ngIf="!!(getMyObj$ | async) as obj">
  <div>{{ obj }}</div>
</div>

My thought would be that my console show me the getting my Obj again and again until the expiry date is overdue, and then to see the alert message : OBJ EXPIRED with the console message CONSOLE NULL once. But currently, after the getting my Obj message, I have infinite CONSOLE NULL messages (that makes my browser crash) and the alert event is never shown.

Any one got any idea ? I have no idea what could makes that crash like that.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is probably because of angular change detection, causing it to repeatedly call that method and subscribe to a new observable each time. You should instead create the observable once and share it:

this.getMyObj$ = 
  interval(1000).pipe(
    concatMap(() => this.getSessionData<MyObj>(this._myObj)),
    takeWhile(myObj => myObj != null),
    tap(x => console.log('getting my Obj'),
    shareReplay(1)
  );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!