knnhcn
knnhcn

Reputation: 1151

RxJS skipWhile boolean is true

I have the following use-case:

There is a service which queues calculation tasks with a certain ID. I hooked up an observable to query the status of the service. As long as the ID is in the queue, the query returns true (not calculated yet). Once the query is false, it means the task has been calculated.

I'm looking for a possibility for the observable to only emit once the returned value is false. So far I have tried with .skipWhile and .filter, but could not achieve the desired behaviour.

private calc = new Subject<T>();

calculate(id: number): Observable<T> {
    this.calcService.searchID(id).filter((x: boolean) => x == false)
         .subscribe((dat: boolean) => {
              this.calc.next(T);
    });
    return this.calc.share();
  }

or

calculate(id: number): Observable<T> {
    this.calcService.searchID(id).skipWhile((x: boolean) => x == true)
         .subscribe((dat: boolean) => {
              this.calc.next(T);
    });

    return this.calc.share();
  }

(I'm sorry for using == true/false)

Hope someone can give me a hint. I'm using RxJS 6.

Edit: Sorry I missed something. this.calcService.searchID(id) is an HTTP request. And on every request it returns the boolean. So I might get false after 20 requests or after 100. It depends on the service how fast the calculation is. So I need a possibility to either wait until false comes back, or redo the request until I get false.

Upvotes: 2

Views: 2435

Answers (1)

user776686
user776686

Reputation: 8665

You need to wrap the service calls in an observable that will monitor the series of service calls. Service call will always emit a single value and complete.

Look at this stackblitz: https://stackblitz.com/edit/typescript-dwmwls?file=index.ts

One comment though: you should be careful with first(predicate) - even though it does the job, it will throw an error on completion if no value satisfying the predicate has been emitted. Otherwise you might use filter(predicate) + take(1).

If you replace first with skipWhile + take(1) - you should be good too. There is often a couple of ways to achieve same result in rxjs.

Upvotes: 1

Related Questions