admin管理员组

文章数量:1410674

With rxjs 7.5.7, I return a promise when a polling http request will finally returns true after several false values, but takeUntil used is never called again.

I tried to following code:

return timer(0, 5000).pipe(
  takeUntil(this.http.get('https://testapi/isTrue'))
    .pipe(filter((isTrue: boolean) => {
      return isTrue; // filter method filters false values so they are not emitted
    }))
  )
).toPromise();

Note: https://testapi/isTrue returns false several times and true at the end.

But after the first call to the http query request this.http.get() initiated by the timer whose call result is false, nothing happens after 5 seconds of timer, no error, this.http.get() in takeUntil is not called anymore.

So what is wrong with my instructions?

Note 2: The promise returned is correctly consumed

With rxjs 7.5.7, I return a promise when a polling http request will finally returns true after several false values, but takeUntil used is never called again.

I tried to following code:

return timer(0, 5000).pipe(
  takeUntil(this.http.get('https://testapi/isTrue'))
    .pipe(filter((isTrue: boolean) => {
      return isTrue; // filter method filters false values so they are not emitted
    }))
  )
).toPromise();

Note: https://testapi/isTrue returns false several times and true at the end.

But after the first call to the http query request this.http.get() initiated by the timer whose call result is false, nothing happens after 5 seconds of timer, no error, this.http.get() in takeUntil is not called anymore.

So what is wrong with my instructions?

Note 2: The promise returned is correctly consumed

Share Improve this question edited Mar 6 at 6:45 Naren Murali 60.7k5 gold badges44 silver badges80 bronze badges asked Mar 6 at 6:19 magneticcoremagneticcore 132 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Use a combination of filter which allows only positive values.

Then we use first to stop the stream leaving only the first positive emission.

import './style.css';

import { of, switchMap, timer, first, filter } from 'rxjs';
let count = 0;
const api = () => {
  count++;
  console.log(count);
  return count > 5 ? of(true) : of(false);
};

timer(0, 500)
  .pipe(
    switchMap(() => api()),
    filter((data: boolean) => data),
    first()
  )
  .subscribe(console.log);

// Open the console in the bottom right to see results.

Stackblitz Demo

本文标签: angularhttp poller using rxjs timer and waitUntil doesn39t workStack Overflow