Create infinite repeatable Observable from array

一曲冷凌霜 提交于 2019-12-11 03:44:47

问题


Let's say I have an array items

I know I can create an observable from this array using

Rx.Observable.fromArray(items)

How do I create a lazily infinitely repeating observable from this (i.e.: repeating the items as long as they are being requested)?

Tried

Rx.Observable.fromArray(items).repeat()

But this doesn't execute lazily and therefor locks up the browser.


回答1:


You cannot do this with an Observable. You way want to look at using an Enumerable.

The Enumerable flavor of Reactive Extensions is known as Interective Extensions.




回答2:


I'm still a newcomer to RxJS, so perhaps what I am proposing is complete madness, but could something along the lines of the following work for this?

var items = [1, 2, 3, 4, 5];

var infiniteSource = Rx.Observable.from(items)
  .map(function (x) { return Rx.Observable.return(x).delay(1000); })
  .concatAll()
  .doWhile(function(_) { return true; /* i.e. never end */ });

infiniteSource.subscribe(function(x) { console.log(x); });

I have an example here: http://ctrlplusb.jsbin.com/sihewo/edit?js,console

The delay is put in there so as not to flood the console. In terms of the "until no longer needed part" perhaps an unsubscribe or other mechanism can be injected into the doWhile?



来源:https://stackoverflow.com/questions/25893983/create-infinite-repeatable-observable-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!