0

What's the best approach to transform an array and call few observable methods inside.

What I am looking for is something of this type to work:

   resultArray = someArray.map(item => {
      oneObs.subscribe(result1 => {
           item.result1 = result1
      });
      secondObs.subscribe(result2 => {
           item.result2 = result2
      });
   });

What is the best approach here? I came up only with a workaround to use the forEach loop of this kind:

   someArray.forEach(item => {
      Observable.forkJoin([oneObs, secondObs]).subscribe(
        (results: [Result1Type, Result2Type]) => {
           item.result1 = results[0];
           item.result2 = results[1];
           resultArray.push(item);
       });
    });

Any help appreciated.

1 Answer 1

4

Your trying to mix synchronous and asynchronous code, which might lead to some weird behavior. My recommendation would be to convert the array to an observable (making the array asynchronous) getting the results and then converting the completed result to an array again:

Observable.from(someArray) // 1
    .mergeMap(item => Observable.forkJoin(oneObs, twoObs)
            .map(results => {
                item.result1 = results[0];
                item.result2 = results[1];
                return item;
            }))
    .toArray() // 2
    .subscribe(arr => resultArray = arr);
  1. Create an observable based on the array
  2. Wait for all observables to finish and create an array with all the resulting values
Sign up to request clarification or add additional context in comments.

Comments

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.