Pause RxJS stream based on a value in the stream

前端 未结 6 484
一生所求
一生所求 2021-01-03 23:56

I have a simple component with a single button that starts and pauses a stream of numbers generated by RxJS timer.

import { Component, OnInit } from \'@angul         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-01-04 00:18

    Here is a simple way to do it. Use the timer() just as an emitter, and increment a count separately. This gives you a little more direct control.

    export class AppComponent implements OnInit {
      active = true;
      out$: Observable;
    
      count = 0;
    
      ngOnInit(): void {
    
        const stream$ = timer(500, 500);
    
        this.out$ = stream$.pipe(
          filter(v => this.active),
          map(v => {
            this.count += 1;
            return this.count;
          }),
          tap(v => {
            if (this.count % 5 === 0) {
              this.active = false;
            }
          })
        )
      }
    
    }
    

    https://stackblitz.com/edit/angular-nzs7zh

提交回复
热议问题