javascript - RXJS。每隔几秒从媒体流中获取值(value)

标签 javascript rxjs reactive-programming

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

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

const int = interval(5000);

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

如有任何帮助,我们将不胜感激

最佳答案

使用switchMap代替

“switchMap 和其他展平运算符之间的主要区别在于取消效果。每次发射时,先前的内部可观察值(您提供的函数的结果)都会被取消,并订阅新的可观察值。” 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));
      }
}

关于javascript - RXJS。每隔几秒从媒体流中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58459061/

相关文章:

javascript - 如何使用 JavaScript 从 ASP.NET Core Web 应用程序获取 JSON 信息

php - 自动从数据库中选择

javascript - Rivets.js 中的 Angularscope.$watch() 等效项

Angular 6 http.delete 请求不起作用

c# - 将可观察字节数组转换为对象

javascript - 使用javascript提取和粘贴字符串的一部分

javascript - Typescript Observables http.post 和 http.get 处理问题

angular - http.get() 不返回可观察值

ios - 如何创建一个只接收一次信号然后取消订阅/释放自己的 ReactiveCocoa 订阅者?

haskell - 如何使用 Shake 库构建响应式(Reactive)构建系统?