I am working on an inactivity timeout for my app. When inactivity is detected, a modal is launched. The modal displays a timer to the user. When the timer (which is a counter) hits 0, I want to be able to "know" the counter is 0 so I can implement the logic to sign-off the user.
export class IdleModalComponent implements OnInit {
counter$: Observable<number>;
count = 300 // 5 minutes for the user to respond before we implement the inactivity logic
constructor(public dialogRef: MatDialogRef<IdleModalComponent>) {
this.counter$ = timer(0, 1000).pipe(
take(this.count),
map(() => (--this.count)),
);
}
}
When I bind the counter observable in the HTML, it accurately displays the countdown. All I need is to be able to capture when:
this.count === 0
.
Timer emit numbers in sequence every specified duration. .
To use map function idiomatically, do not cause any side effects in it, just map the received value.
Finally, to observe the completion:
const initialCounter = 10;
timer(0, 100)
.pipe(
take(initialCounter),
map(v => initialCounter-v))
.subscribe({
next: v => console.log(v),
complete: () => console.log('finished')
});
You can use tap
rxjs operator without directly subscribing like the following :
this.counter$ = timer(0, 1000).pipe(
take(this.count),
map(() => (--this.count)),
tap(val => {
if (val === 0) {
// do what you want such as show modal
alert('The count is 0');
}
})
)
It's when the this.counter$
is completed.
this.counter$
.subscribe(
() => {}, // each time of count update
() => {}, // error
() => {
// completed and `this.count === 0`
}
)
Working Demo
https://stackblitz.com/edit/rxjs-timer-complete?file=src/app/app.component.ts
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.