I have a check which needs to combine 2 checks:
- The first check is an observable to tell if the user is logged
- The second check is a function which can return a boolean or an Observable
Is there a more elegant way of wrapping a value in an observable only if not observable already? Or is there a way to combine the first check with the second when the second is Observable? Or still refactor all this in a more efficent way?
Of course this code is an example to simulate what I get in the real app (see comments in code).
const getRandomBool: () => boolean = () => Math.random() >= 0.5;
const getRandomCheck: () => boolean | Observable<boolean> = () => {
return getRandomBool() ? getAsyncCheck() : getSyncCheck();
};
const myFunction = (): Observable<boolean> | boolean => {
// First check telling if user is logged, which the UserService returns as Observable<boolean>
return of(getRandomBool())
.pipe(
mergeMap((isLogged) => {
// This is the check which can be either boolean or Observable<boolean>
const myCheck = getRandomCheck();
return isLogged
? iif(() => typeof myCheck === 'boolean', of(myCheck), myCheck)
: of(!1)
})
)
};
``