[RxJS] Asyncsubject

Source: Internet
Author: User

Asyncsubject emit The last value of a sequence only if the sequence completed. This value was then cached Forever, and any other Observer that subscribes after the value have been emmitted would receive it right away.

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

varSubject =NewRx.asyncsubject ();varDelayedrange = Rx.Observable.range (0,5). Delay ( +);d elayedrange.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:

functiongetproducts (URL) {varsubject; returnRx.Observable.create (function(Observer) {//If first time, then create Asyncsubject    if(!subject) {Subject=NewRx.asyncsubject (); //Subscribe to SubjectRx.DOM.get (URL). Subscribe (subject); }    //If subject already exists, then just subscribe observer    returnSUBJECT.SUBSCRIBE (Observer); })}varProducts = getproducts ('/products ');//Would trigger request and receive the response when readProducts.subscribe (functionOnNext (Result) {Console.log (' result 1: '), Result.response)},functionOnError (Error) {Console.log (' error '), error)});//Would receive the result immediately because it is cachedSetTimeout (function() {Products.subscribe (functionOnNext (Result) {Console.log (' Result 2: '), Result.response)},functionOnError (Error) {Console.log (' error '), Error)} )}, 5000)

[RxJS] Asyncsubject

Related Keywords:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.