[RxJS] Get current value out of Subject (BehaviorSubject)

When you want to get the current value of a subject, you need to switch BehaviorSubject, it always emit the latest value or throw error.

Then you can call 'getValue()':

var subject = new Rx.BehaviorSubject(56);

console.log('Value is: ' + subject.getValue());

// => Value is: 56

subject.onNext(42);

console.log('Value is: ' + subject.getValue());

// => Value is: 42

subject.onCompleted();

subject.onNext(100);

console.log('Value is frozen: ' + subject.getValue());

// => Value is frozen: 42

subject.dispose();

try {
    subject.getValue();
} catch (e) {
    console.log(e.message);
}

// => Object has been disposed

 

posted @ 2018-07-17 02:11  Zhentiw  阅读(309)  评论(0编辑  收藏  举报