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)
时间: 2024-10-07 01:08:58