4

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.

Yousef
  • 876
  • 6
  • 13

2 Answers2

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.

cwharris
  • 17,835
  • 4
  • 44
  • 64
  • For a small explanation: Observables are pushed to the receiver, while Enumerables are pulled by the receiver from the source, so you'd want an infinite Enumerable, and the consumer would simply stop pulling when it doesn't need any more items. – Manuel Schweigert Sep 18 '14 at 08:57
  • Thanks, that makes sense. This post: http://stackoverflow.com/questions/25524671/rxjs-zip-is-not-lazy - confused me and made me believe I could do observable1.zip("infinitearrayobservable") to get a new combination whenever observable1 produces a new value. How would you accomplish this instead? Just subscribe to observable1 and use my own logic to select an item from the array? – Yousef Sep 18 '14 at 10:05
0

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?

ctrlplusb
  • 12,847
  • 6
  • 55
  • 57