For example, we have following code:
import { of, defer} from 'rxjs'; class Foo { private num = 123 onum = of(this.num); updateNum(val) { this.num = val; } } const f = new Foo(); f.onum.subscribe(x => console.log(x)) // 123
If I want to update the 'num' before subscribe:
import { of, defer} from 'rxjs'; class Foo { private num = 123 onum = of(this.num); updateNum(val) { this.num = val; } } const f = new Foo(); f.updateNum(321) f.onum.subscribe(x => console.log(x)) // 123
The final value is still '123'.
This is because 'of()' remember the value during the construction time. So it is always 123.
How to solve the problem? Using defer.
import { of, defer} from 'rxjs'; class Foo { private num = 123 onum = defer(() => of(this.num)); updateNum(val) { this.num = val; } } const f = new Foo(); f.updateNum(321) f.onum.subscribe(x => console.log(x)) // 321
'defer' lazy evaluate the value during the time we call subscribe