ReactiveX / rxjs

A reactive programming library for JavaScript
https://rxjs.dev
Apache License 2.0
30.68k stars 3k forks source link

iif subscriptions #7488

Closed borosbela closed 2 months ago

borosbela commented 2 months ago

Describe the bug

The documentation says, that only trueResult of the given observables will be subscribed, but both of the falseResult and trueResult will be subsrcibed to, and only returns the trueResult observable's value.

Expected behavior

Only subsrcibe to the trueResult observable.

Reproduction code

iif(() => false,
 firstObs(),
 secondObs()
)

function firstObs(): Observable<string> {
 console.log("Why?"); // <--- this got logged
 return of("one way");
}

function secondObs(): Observable<string> {
 console.log("Why not?"); // <--- this got logged
 return of("other way");
}

Reproduction URL

No response

Version

7.8.1

Environment

No response

Additional context

No response

jakovljevic-mladen commented 2 months ago

Hi @borosbela,

If you subscribe to your iif Observable, you'll see that it only logs other way. one way is not logged and will not be logged as long as the function passed as the first parameter to iif returns falsy value. Please visit this link for demo.

The reason why Why? gets logged is because you're actually calling firstObs function when preparing the second parameter for iif which calls console.log("Why?") before returning of("one way"). This has nothing to do with RxJS, it's just how JavaScript works.

If you need to postpone execution of firstObs, you can use this:

import { defer, iif } from 'rxjs';

iif(() => false,
 defer(firstObs),
 defer(secondObs)
)

I'm gonna close this issue as there's no bug here.