首页 > Web开发 > 详细

[RxJS] defer() lazy evaluation

时间:2020-04-27 01:08:34      阅读:91      评论:0      收藏:0      [点我收藏+]

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

[RxJS] defer() lazy evaluation

原文:https://www.cnblogs.com/Answer1215/p/12783796.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!