码迷,mamicode.com
首页 > Web开发 > 详细

[RxJS] AsyncSubject

时间:2016-08-17 06:45:21      阅读:453      评论:0      收藏:0      [点我收藏+]

标签:

AsyncSubject emit the last value of a sequence only if the sequence completed. This value is then cached forever, and any other Observer that subscribes after the value has been emmitted will receive it right away.

 

AsyncSubject is convenient for asynchronous operations that return a single value, such as Ajax requests.

 

var subject = new Rx.AsyncSubject();
var delayedRange = Rx.Observable.range(0,5).delay(1000);

delayedRange.subscribe(subject);

//----[0,1,2,3,4]|
//  AsyncSubject
//----4|

subject.subscribe(
  function onNext(item) { console.log(Value:, item); },
  function onError(err) { console.log(Error:, err); },
  function onCompleted() { console.log(Completed.); }
)

/*
"Value:"
4
"Completed."
*/

 

A more useful example:

function getProducts(url){
  var subject;
  
  return Rx.Observable.create(function(observer){
    //If first time, then create AsyncSubject
    if(!subject){
      subject = new Rx.AsyncSubject();
      //Subscribe to subject
      Rx.DOM.get(url).subscribe(subject);
    }
    //If subject already exists, then just subscribe observer
    return subject.subscribe(observer);
  })
}

var products = getProducts(‘/products‘);

// Will trigger request and receive the response when read
products.subscribe(
  function onNext(result) {console.log(‘Result 1: ‘, result.response)},
  function onError(error) {console.log(‘ERROR‘, error)}
);

// Will receive the result immediately because it is cached
setTimeout(function(){
  products.subscribe(
    function onNext(result) {console.log(‘Result 2: ‘, result.response)},
    function onError(error) {console.log(‘ERROR‘, error)}
  )
}, 5000)

 

[RxJS] AsyncSubject

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5778453.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!