8

I have following pseudocode

objects = [obj1, obj2, obj3]    
for obj in objects {
user: http.get(obj1.user_id)
product: http.get(obj1.product_id)
}.subscribe(results => {

do something with results

})

What I want here is that, I loop through an array of objects and for each object get related user and product and then subscribe to do something with the user and product. How can I do that?

1

2 Answers 2

12

You could use RxJS forkJoin along with Array#map to trigger multiple observables in parallel.

const objects = [obj1, obj2, obj3];

forkJoin(
  objects.map(obj =>           // <-- `Array#map` function
    forkJoin({
      user: http.get(obj.user_id)
      product: http.get(obj.product_id)
    })
  )
).subscribe({
  next: (res) => {
    console.log(res);
    // use `res`
  },
  error: (err) => {}
});


/*
output in subscription: 
[
  { 
    user: result from `http.get(obj1.user_id)`,
    product: result from `http.get(obj1.product_id)`,
  },
  { 
    user: result from `http.get(obj2.user_id)`,
    product: result from `http.get(obj2.product_id)`,
  },
  { 
    user: result from `http.get(obj3.user_id)`,
    product: result from `http.get(obj3.product_id)`,
  }
]
*/
Sign up to request clarification or add additional context in comments.

1 Comment

How to console.log the results inside subscribe?
3

You could use the zip() operator to combine your requests and execute some code once every request has finished:

const sourceOne = http.get(obj1.product_id);
const sourceTwo = http.get(obj2.product_id);

zip(sourceOne, sourceTwo).subscribe(val => {
    // do something
});

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.