I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet:
public dummyStream(): Observable<number> {
return of(true).pipe(
switchMap(isTrue =>
iif(() => isTrue === true,
combineLatest([of([1,2,3,4,5]), of(2)]).pipe(
map(([arrayOfNumbers, multiplier]) => {
const results = arrayOfNumbers.map(num => {
if (num !== 5) return num;
else return 4;
});
return results.reduce((prev, curr) => prev + curr, 0);
})
),
combineLatest([of([1,2,3,4,5]), of(2)]).pipe(
map(([arrayOfNumbers, multiplier]) => {
return 0;
})
)
)
)
);
}
By starting with of(true)
, we always get to the iif()
condition as it is predetermined to be true in this example.
Within this structure, I utilize combineLatest
to merge two observables. Subsequently, I apply arrayOfNumbers.map
to transform numbers unless they are equal to 5, in which case I replace them with 4.
The challenge arises when I try to return of(num * multiplier)
. This causes the map
function to potentially return either a number
or Observable<number>
, leading to compatibility issues.
To tackle this, I modified the code so that instead of returning a number, I return an Observable<number>
in the else block:
public dummyStream(): Observable<number> {
return of(true).pipe(
switchMap(isTrue =>
iif(() => isTrue === true,
combineLatest([of([1,2,3,4,5]), of(2)]).pipe(
map(([arrayOfNumbers, multiplier]) => {
const results = arrayOfNumbers.map(num => {
if (num !== 5) return num;
else of(num * multiplier);
});
return results.reduce((prev, curr) => prev + curr, 0);
})
),
combineLatest([of([1,2,3,4,5]), of(2)]).pipe(
map(([arrayOfNumbers, multiplier]) => {
return 0;
})
)
)
)
);
}
Now I aim to adjust the implementation so that the return type of dummyStream()
remains as Observable<number>
, while incorporating another observable within the else block. How can I achieve this?