【问题标题】:RXJS. Get value from media stream every few secondsRXJS。每隔几秒从媒体流中获取价值
【发布时间】:2019-10-18 22:56:58
【问题描述】:

我目前有一个 observable(称为 videoStreams.currentTime$),它发出的视频播放器当前位置的频率低于每秒​​。如何获取当前时间(可观察对象发出的值),但每 5 秒左右?

这是我得到的最接近的结果,但是每次发出值时,发出结果的次数都会增加。

const int = interval(5000);

const subscription = int
  .pipe(flatMap(() => videoStreams.currentTime$))
  .subscribe(val => console.log("TIME", val));

任何帮助将不胜感激

【问题讨论】:

  • 我不确定你的目的是什么,但你能用switchMap instea of​​ flatMap 告诉我们结果吗?

标签: javascript rxjs reactive-programming


【解决方案1】:

原来使用下面这个很简单

 const curTime$ = videoStreams.currentTime$.pipe(
  throttle(() => interval(10000))
);

它不是每三分之一秒左右返回玩家的位置,而是通过限制它返回时间点(我分配给它)的值。

【讨论】:

  • 这是来自<video> elm 的流吗?你会为你的答案设置一个 Stackblitz 吗?
【解决方案2】:

请改用switchMap

“switchMap 和其他扁平化操作符的主要区别在于取消效果。在每次发射时,先前的内部 observable(您提供的函数的结果)被取消并订阅新的 observable。”read more on switchMap

stackblitz example

import { Component } from '@angular/core';
import { interval,of } from 'rxjs';
import { flatMap,switchMap } from 'rxjs/operators';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  currentTime$ = of(1,2,3,4,5,6,7,8)
  ngOnInit() {
    const int = interval(5000);

    const subscription = int
      .pipe(switchMap(() => this.currentTime$ ))
      .subscribe(val => console.log("TIME", val));
      }
}

【讨论】:

    猜你喜欢
    • 2016-10-03
    • 2019-11-25
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多