Question: Combining Observables - waiting 'til all observables fire

Question

Combining Observables - waiting 'til all observables fire

Answers 2
Added at 2017-01-03 22:01
Tags
Question

I have this code

let $obs = Rx.Observable.merge(
    this.obsEnqueue,
    Rx.Observable.timer(2000)
);

but this isn't doing want I want - want I would like to do is wait until both events fire (an event from this.obsEnqueue and the event from Rx.Observable.timer()).

merge will most likely create a new Observable that will fire when the first event happens from all the observables are passed in. I would like to create a new observable that will fire after all observable passed in have fired.

So more generally:

let $obs = Rx.Observable.X(
    Rx.Observable,    // wait
    Rx.Observable,    // until
    Rx.Observable,    // all of these
    ...
    Rx.Observable     // fire the next event
);

How can I do this? What is X?

Answers
nr: #1 dodano: 2017-01-03 22:01

You could maybe use forkJoin:

Rx.Observable.forkJoin(
  Rx.Observable.of('hello').delay(2000),
  Rx.Observable.of('world').delay(1000)
)
  .subscribe(console.log)

After two seconds you should have an array of ['hello', 'world']. The order of the output will be the same order as the input of arguments.

Input can be multiple arguments, an array, and other things:

Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.

Here is a Fiddle to test it (just bring up the console).

nr: #2 dodano: 2017-01-03 22:01

You can use zip, if you want to combine all the results when they arrive:

const { Observable } = Rx;

const result = Observable.zip(
  Observable.of('data1'),
  Observable.of(true).delay(500),
  Observable.timer(1000)
);

result.forEach(console.log); // after 1000ms: ['data1', true, 0]
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.min.js"></script>

Source Show
◀ Wstecz