简体   繁体   English

rxjs中的动态计时器

[英]Dynamic timer in rxjs

I am creating a slider with images and videos and am want to assign a certain amount of screen time for each type. 我正在创建一个包含图像和视频的滑块,并且希望为每种类型分配一定数量的屏幕时间。

let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{"path":"http://localhost:8091/public/testvideo.mp4","type":"video"}]
Observable.timer(0, 3000)
                            .map(e => { 
                                console.log(e); return data[e % data.length]; 
                            })
                            .subscribe(item => {
                                this.activeItem = item;
                            });

I am able to set a generic time for all the slides using the code above but am unable to do set separate values for each of the items in the array. 我可以使用上面的代码为所有幻灯片设置通用时间,但无法为数组中的每个项目设置单独的值。

Here is what I actually want to achieve 1) Iterate through the array from 0 to the last index once it has completed iterating infinitely 2) To be able to set a time when the next iteration takes place based on the type property inside each object. 这实际上是我要实现的目标:1)完成无限迭代后,从0遍历数组到最后一个索引2)能够根据每个对象内部的type属性设置下次迭代发生的时间。

Right now only 1) is satisfiable. 目前只有1)是可以满足的。

The trick would be to use concatMap. 诀窍是使用concatMap。 It will create from each item an immediate observable with the item followed by a delay of an empty Observable. 它将从每个项目创建一个可立即观察到的项目,然后延迟一个空的Observable。 After that delay the observable completes, and the next one will be concatenated. 在该延迟之后,可观察对象完成,并且下一个对象将被串联。 This will be repeated infinitely with the repeat() operator. 这将使用repeat()运算符无限重复。

let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{"path":"http://localhost:8091/public/testvideo.mp4","type":"video"}];

const delayByMediaType = {image: 1000, video: 5000};

Observable.from(data)
    .concatMap(media => 
        Observable.of(media).concat(Observable.empty().delay(delayByMediaType[media.type]))
    )
    .repeat()
    .do(console.log)
    .subscribe(item => this.activeItem = item);
let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{ "path":"http://localhost:8091/public/testvideo.mp4","type":"video"}];

const delayByMediaType = {image: 1000, video: 5000};

Observable.from(data)
.concatMap(media => {
   return Observable.of(media).delay(delayByMediaType[media.type])
}).subscribe(console.log);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM