[RxJS] defer() lazy evaluation

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

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12783796.html