softshipper
softshipper

Reputation: 34099

Why Rx.Observable.of(true) starts to emit

I have following code:

console.log('start');

//emit value every second
const message = Rx.Observable.interval(1000);
//emit value as soon as subscribed
const trueObs = () => Rx.Observable.of(true);
// start emitting delayed values as soon as trueObs emits
const delayWhenExample = message.delayWhen(trueObs);
//log values start logging after one second
//ex. output: 0...1...2...3
const subscribe = delayWhenExample.subscribe(val => console.log(val));
<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.umd.js"></script>

Why Rx.Observable.of(true) starts to emit value without subscribe the observable?
I understand the concept to RxJS as lazy evaluation, it does not emit values, until I am asking it.

Upvotes: 1

Views: 1191

Answers (2)

user3743222
user3743222

Reputation: 18665

I am not too familiar with Rxjs v5 but here is probably what is happening :

  • you subscribe to delayByExample, which is message.delayWhen(delayForFiveSeconds)
  • this in turns leads to subscription to delayForFiveSeconds as probably the delayWhen operator subscribes to both its operands i.e. delayWhen(message, delayForFiveSeconds) leads to subscription to both message and delayForFiveSeconds and then the value read from message is passed forward when a value from delayForFiveSeconds is received. But both subscriptions occurs at the time of subscription to delayWhen.
  • last thing is that Rx.Observable.of(true) will emit synchronously on subscription
  • so, delayWhenExample.subscribe(val => console.log(val)) will immediately trigger the emission of true

If you want to understand more precisely the chain of subscription taking place, you can refer to the following SO answer which comes with illustrated dataflows :

Upvotes: 1

Peter Hall
Peter Hall

Reputation: 58785

Your variable delayWhenExample is actually a SubscriptionDelayObservable observable, which was created by calling delayWhen(). It keeps track of the original message observable and the observable that you passed to it as an argument (delayForFiveSeconds). When you call subscribe(), it will also subscribe behind the scenes to both of these observables, which it needs to calculate its values.

This is really the whole idea of lazy evaluation. You subscribe to the observable that you need, and all of the other observables that it depends on will be subscribed to automatically - but only when necessary. Unsubscribing is also done automatically, which is very convenient when combining data from a lot of different sources.

Upvotes: 1

Related Questions