Reputation: 407
I have a problem with RXJS logic. I would like to create an interval with changing values of my Subject. The case is I would like to show an element on the page, after 5 seconds. It should be shown for 10 seconds, after that it disappears. After next 5 seconds, it should appear once again, and so on, disappeared after 10 seconds. For example if I set option to show popup after 5 seconds from page load, my popup appears for 10 seconds, after that it disappears. 5 seconds later it should show again, and so on. I have no idea how to make it work, because timings can be for example:
So second subscription should wait, until previous one finished and changed its value.
This is my code I currently implemented:
private _shouldPopupShow$ = new BehaviorSubject<boolean>(false);
public shouldPopupShow$ = this._shouldPopupShow$.asObservable();
public addPopupMessage() {
this._shouldPopupShow$.pipe(
startWith(0),
switchMap(() => timer(5000)),
repeat()
).subscribe(() => {
this._shouldPopupShow$.next(true);
this._shouldPopupShow$.pipe(
startWith(0),
distinctUntilChanged(),
repeat(),
switchMap(() => timer(10000))
).subscribe(() => {
this._shouldPopupShow$.next(false);
});
});
}
In my code, I would like to start changing value to true, after 5 seconds first to true. After 10 seconds, set it to false. After next 5 seconds, set it to true, after 10 seconds, set it to false and so on. Thank you for help!
Upvotes: 1
Views: 1230
Reputation: 7351
There's a simple solution using interval
import { interval } from 'rxjs';
import { map } from 'rxjs/operators';
public shouldPopupShow$ = interval(5000).pipe(
map(i => i%2 === 0),
);
Upvotes: 0
Reputation: 23813
I think the following should be working:
const shouldPopupBeShown$: Observable<boolean> = timer(5000).pipe(
switchMap(() => merge(of(true), timer(10000).pipe(mapTo(false)))),
repeat()
);
EDIT: it does --> https://stackblitz.com/edit/rxjs-v8frj3?file=index.ts
Upvotes: 2