C
C
Coder3212018-03-16 18:13:40
Angular
Coder321, 2018-03-16 18:13:40

How to properly complete the timer through rxjs?

There is a query like this

Observable.timer(0, 2000)
            .switchMap(() => Observable.if(
                () => this.isBlocked,
                Observable.defer(() => this.http.post(apiPath)
                )
            )
            .catch(err => Observable.empty())
            .subscribe((data: Array<any>) => {
                this.notise = this.mapData(data);
            });

which sends requests on a timer, but there is one problem, firstly, when the variable isBlocked === false, requests do not go, it seems to be normal, but the interval timer continues to work. As if the problem is not significant but not very pleasant. The second problem is that after changing isBlocked to true, you need to immediately send a request. Maybe someone knows how to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmitrygavrish, 2018-03-16
@dmitrygavrish

If you do not need an infinite timer, then it will be easier to refuse it. Regarding the decision "after changing isBlocked to true, you must immediately send a request" - create your own sequence, which you will iterate with the value you need at the right time (code for example):

class SomeComponent {
    private _isBlocked$$: Subject<boolean> = new Subject();
    public isBlocked$: Observable<boolean> = this._isBlocked$$.asObservable();

    public ngOnInit(): void {
        this.isBlocked$
            .switchMap((isBlocked: boolean) =>
                isBlocked ? this.http.post(apiPath) : Observable.of(null))
            .subscribe((data: Array<any>) => {
                if (data !== null) {
                    this.notise = this.mapData(data);
                }
            });
    }

    public someMethod(bool: boolean): void {
        this._isBlocked$$.next(bool);
    }
}

If you still want to leave the timer and stop at a specific moment, then takeUntil will do:
Observable.timer(0, 2000).takeUntil(this.isBlocked$)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question