播放和暂停间隔rxjs

播放和暂停间隔rxjs,rxjs,intervals,rxjs6,Rxjs,Intervals,Rxjs6,我正在尝试使用Rxjs库实现播放和暂停按钮 const play$ = fromEvent(playerImplementation, PLAYER_EVENTS.PLAY).pipe(mapTo(true)); const pause$ = fromEvent(playerImplementation, PLAYER_EVENTS.PAUSE).pipe(mapTo(false)); const waiting$ = fromEvent(playerImplementation, PLAYER

我正在尝试使用Rxjs库实现播放和暂停按钮

const play$ = fromEvent(playerImplementation, PLAYER_EVENTS.PLAY).pipe(mapTo(true));
const pause$ = fromEvent(playerImplementation, PLAYER_EVENTS.PAUSE).pipe(mapTo(false));
const waiting$ = fromEvent(playerImplementation, PLAYER_EVENTS.WAITING).pipe(mapTo(false));

let counterTime = 0;
const currentTime$ = interval(30).pipe(
 map(()=>counterTime += 30));

const player$ = merge(play$, pause$, waiting$).pipe(
        switchMap(value => (value ? currentTime$ : EMPTY)));

// DIFFERENCE IN RESULTS
currentTime$.subscribe((v)=> console.log("Regular Count " + v)); // get correctly 30,60,90,120...
player$.subscribe((v)=>console.log("Condition Count" + v)); // get wrongly 30,150,270, 390

有人能帮助理解为什么结果之间存在差异吗

之所以发生这种情况,是因为我使用了多个订阅者作为一个可观察对象(player$observable)。我通过使用ReplaySubject而不是Observable来解决这个问题,并通过使用多播来处理多个订阅者中的事件,而不改变值

const play$ = fromEvent(playerImplementation, PLAYER_EVENTS.PLAY).pipe(mapTo(true));
const pause$ = fromEvent(playerImplementation, PLAYER_EVENTS.PAUSE).pipe(mapTo(false));
const waiting$ = fromEvent(playerImplementation, PLAYER_EVENTS.WAITING).pipe(mapTo(false));

  let timeCounter = 0;
  const source = Observable.create((obs : Observer<number>)=> {
          interval(30).pipe(
             map(() => timeCounter += 30)).subscribe(obs);
          return () => {};
        });

        // Cast the observable to subject for distributing to several subscribers
        const currentTime$ = source.pipe(multicast(()=> new ReplaySubject(5))).refCount();

  const player$ = merge(play$, pause$, waiting$).pipe(
        switchMap(value => value ? currentTime$ : EMPTY));
const play$=fromEvent(playerImplementation,PLAYER_EVENTS.play).pipe(映射到(true));
const pause$=fromEvent(playerImplementation,PLAYER_EVENTS.pause).pipe(映射到(false));
const waiting$=fromEvent(playerImplementation,PLAYER_EVENTS.waiting).pipe(映射到(false));
设计时器=0;
常量源=可观察。创建((obs:Observer)=>{
间隔(30)。管道(
map(()=>timeCounter+=30)).subscribe(obs);
return()=>{};
});
//将可观察对象强制转换为主题,以便分发给多个订阅者
const currentTime$=source.pipe(多播(()=>newreplaysubject(5)).refCount();
const player$=合并(play$、pause$、waiting$).pipe(
开关映射(值=>value?currentTime$:空);

如果使用全局变量,会发生不好的事情。如果所有流都增加了相同的变量,那么结果怎么可能相等呢?@itays02那么您可以记录您的事件吗?播放$、暂停$、等待$。当你停止计数时,我不会从玩家$那里得到你所期望的。你想把间隔时间定在2点吗?