1

I need to merge two same type observables and return same type observable in Angular2 function.
So all I want to do is:

from this:

obs1.subscribe(obs => console.log(obs))
(where I get): 
{
   count: 10,
   array: <someObservable[]> 
}

and

obs2.subscribe(obs => console.log(obs))
(where I get): 
{
   count: 10,
   array: <someObservable[]> (different objects)
}

into:

{
   count: 10 (count always the same number),
   array: <someObservable[]> (combined array from obs1 and obs2)
}

What is the simplest way to achieve that? (Maybe it is simple to even junior level angular developer, but I have to it quickly and Im newbie in this sphere). Thanks in advice.

---UPDATE---

from this code part :

const obs2 = obs1.pipe(
        switchMap(value => {
          return this._loadMoreTextSearchSub.asObservable()
          .pipe(pairwise(),
          map(params => this.getPagingParameters(params[0], params[1])),
          switchMap(request),
          map(response => response.packages),
          scan<SearchPackage[]>((all, current) => {
            return [...all, ...current];
          }, 
          value.packages
          ));
        }))
        .subscribe(data => console.log('sec', data));

I get array of objects. How could I wrap that array into the object and set extra property - 'count'?

Current:
[{...}, {...}, {...}, {...}]
Desired:
{count: some_number, array: [{...}, {...}, {...}]}
2
  • It depends on how do you want to call the observables, should they be called subsequently, parallely? Commented May 6, 2020 at 19:22
  • They called subsequently Commented May 6, 2020 at 19:24

1 Answer 1

2

If you need to call the Observables subsequently then you can use mergeMap() for the same.

Lets say, you call obs1 first, once you have the result of obs1, you call obs2, then combine both the results and return.

obs1.pipe(mergeMap((firstResult) => {
    return obs2.pipe(map((secondResult) => {
        return { count: firstResult.count, array: [...firstResult.array, ...secondResult.array] };
    }))

})).subscribe((data) => {
    console.log(data);
})
Sign up to request clarification or add additional context in comments.

3 Comments

Appreciate your help! Is it hard to rewrite code for parallely called observations?
@Karlito Nope, its all the same. You have forkJoin(), combineLatest(), withLatestFrom(), zip(), etc. You can use any of them, depending on your requirement. Just the ways of using them are different.
@Karlito See this link: scotch.io/tutorials/… .Its very nicely explained for some of them'.

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.