1

Currently I have a method that makes 2 separate calls to an API, each returns an observable and in the case that nothing is returned, the observable is set to EMPTY.

I'm currently trying to combine these returned observables and return the combined observable as an observable.

combinedObservables(items1[], items2[]): Observable<Spatial> {
    obs1<Spatial> = iif(items1.length > 0 ? getObsList1 : Empty)
    obs2<Spatial> = iif(items2.length > 0 ? getObsList2 : Empty)

    return combineLatest([obs1, obs2])

The problem is this returns an observable of Spatial | Spatial, rather than just spatial. I tried using forkjoin but I don't think this would work in the case that one was empty as it needs each observable to emit a value

I expected combinelatest would simply combine both streams and return the two as one considering both observables are of the same type and the goal return type is also the same

N.F.
  • 3,844
  • 3
  • 22
  • 53
  • CombineLatest only emits once both have emitted at least once – Andrew Allen Aug 10 '23 at 07:58
  • Is there way to combine them even if the other returns empty, as in either return both, just one or neither – Lewis Patterson Aug 10 '23 at 08:01
  • What are you actually trying to accomplish? Do you want to *merge* the contents of both `Spatials` if both have content, or do you want to just merge the streams into one and then handle each `Spatial` separately? If it's the last, use the `merge` operator. – Daniel B Aug 10 '23 at 08:08
  • I have two types of items that can be added to activities, and I need both of them to show on a map. But users are able to add as many of each item type as they want, so they could only have type 1, or only type 2 or both. So I need to return the results of both – Lewis Patterson Aug 10 '23 at 08:16

2 Answers2

0

Given your type signature, you probably want mergeWith

const a = items1.length ? getObsList1 : empty
const b = items2.length ? getObsList2 : empty

return a.pipe(mergeWith(b)) // Observable<Spatial>

FYI combineLatest combines the streams by putting the most recent from each into a tuple that it emits. It isn't really appropriate for your use case where you just want a single stream that combines items from 2 separate streams.

Brandon
  • 38,310
  • 8
  • 82
  • 87
0

Combining two observables :

//combine two observable 
combineLatest([obs1, obs2]).pipe(map(([a, b]) => ({ a, b}))).subscribe((result) => console.log(result));
Jerry
  • 1,005
  • 2
  • 13