8

I'm creating an array of asynchronous observables with Rx.Observable.create() and hope to use .toArray() to get all the values when they complete.

console.log('running');
let valsArray = ['a','b','c'].map((val,i)=>{
  return Rx.Observable.create((obs)=>{
    let tid = setTimeout(()=>{
      console.log(val + ' timing out');
      obs.onNext(val);
    },i*500);
    return ()=>{
      clearTimeout(tid);
    };
  }).publish().refCount();
});

Rx.Observable.from(valsArray)
.flatMap((v)=>v)
.toArray()
.subscribe((arr)=>{
  console.log("arr should be ['a','b','c']",arr);
});

Above example at http://jsbin.com/wegoha/10/edit?js,console.

Using setTimeout as a stand-in for other asynchronous operations to keep the example simple.

1
  • 1
    You shouldn't link to external site unless it supports the information already in your question. Commented Feb 19, 2016 at 4:17

1 Answer 1

11

The code is correct except you didn't complete the source observables.

The toArray() operator can only work when the observable completes, and since you didn't complete the Rx.Observable.create then your query could never end.

Try this:

console.log('running');
let valsArray = ['a','b','c'].map((val,i)=>{
  return Rx.Observable.create((obs)=>{
    let tid = setTimeout(()=>{
      console.log(val + ' timing out');
      obs.onNext(val);
      obs.onCompleted();
    },i*500);
    return ()=>{
      clearTimeout(tid);
    };
  }).publish().refCount();
});

Rx.Observable.from(valsArray)
.flatMap((v)=>v)
.toArray()
.subscribe((arr)=>{
  console.log("arr should be ['a','b','c']",arr);
});

Also, just as a side-note, the .publish().refCount() seems wrong here. There's no need in this code to make the source observables hot.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Worked like a charm, and now I understand the onCompleted method better. Also checked out the hot and cold observables docs again since I didn't fully understand them. Fantastic description at stackoverflow.com/questions/32190445/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.