[RxJS] merge - build count down example

import { interval, fromEvent, of, merge, empty } from 'rxjs';
import { scan, mapTo, takeWhile, takeUntil, tap, startWith, switchMap } from 'rxjs/operators';

/*
 * CODE FOR FOR FIRST SECTION OF LESSON
 */
// const keyup$ = fromEvent(document, 'keyup');
// const click$ = fromEvent(document, 'click');

// keyup$.subscribe(console.log);
// click$.subscribe(console.log);

/*
 * merge subscribes to all provided streams on subscription,
 * emitting any values emitted by these streams.
 */
// merge(keyup$, click$).subscribe(console.log);


/*
 * BEGIN SECOND SECTION OF LESSON
 */
// elem refs
const countdown: any = document.getElementById('countdown');
const message = document.getElementById('message');
const pauseButton = document.getElementById('pause');
const startButton = document.getElementById('start');

// streams
const counter$ = interval(1000);
const pauseClick$ = fromEvent(pauseButton, 'click');
const startClick$ = fromEvent(startButton, 'click');

const COUNTDOWN_FROM = 10;

/*
 * With merge, we can combine the start and pause
 * streams, taking relevant action below depending
 * on which stream emits a value.
 */
merge(
  startClick$.pipe(mapTo(true)), 
  pauseClick$.pipe(mapTo(false))
)
.pipe(
  /*
   * Depending on whether start or pause was clicked,
   * we'll either switch to the interval observable,
   * or to an empty observable which will act as a pause.
   */
  switchMap(shouldStart => {
    return shouldStart ? counter$ : empty();
  }),
  mapTo(-1),
  scan((accumulator, current) => {
    return accumulator + current;
  }, COUNTDOWN_FROM),
  takeWhile(value => value >= 0),
  startWith(COUNTDOWN_FROM)
)
.subscribe(value => {
  countdown.innerHTML = value;
  if (!value) {
    message.innerHTML = 'Liftoff!';
  }
});

 

 

posted @   Zhentiw  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-10-26 [CSS] Use CSS Transforms to Create Configurable 3D Cuboids
2020-10-26 [CSS] Use CSS Variables Almost like Boolean Values with Calc (maintainable css)
2020-10-26 [Kotlin] Typecheck with 'is' keyword, 'as' keyword for assert type
2020-10-26 [Kotlin] When to add () and when not to
2020-10-26 [Kotlin] fold / reduce
2016-10-26 [CSS] Control Image Aspect Ratio Using CSS (object-fit)
2016-10-26 [Angular2 Form] Reactive form: valueChanges, update data model only when form is valid
点击右上角即可分享
微信分享提示