[RxJS] AsyncSubject

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

[RxJS] AsyncSubject的相关文章

关于rxjs subject订阅分发实现Angular的全局数据管理与同步更新

自定义实现angular中数据的状态管理,如有不妥请指正 一.先介绍一下rxjs中subject: Import {subject}from’rxjs’ Subject 数据的订阅与分发,结合报刊的发布与订阅进行功能的模拟,subject即是observeable对象也是observer对象,subject对于后期没有数据更新时所添加的订阅者是不怎么友好的,因为不跟新数据时订阅者就不在收到返回的数值     const interval$ = interval(1000).pipe(take(1

[RxJS] Multicasting shortcuts: publish() and variants

Because using multicast with a new Subject is such a common pattern, there is a shortcut in RxJS for this: the publish() operator. This lesson introduces publish() and its variants publishReplay(), publishBehavior(), publishLast(), share(), and shows

[译]RxJS 5.X基础篇

欢迎指错与讨论 : ) 当前RxJS版本:5.0.0-beta.10.更详细的内容尽在RxJS官网http://reactivex.io/rxjs/manual/overview.html.文章比较长,可以通过快捷键 command+f 或者 alt+f 搜索主要内容. - 前言  RxJS在ng2.react( mobx ) 中扮演一个重要角色,因此笔者想学好RxJS,提前做好准备.本文95%非原创,而是笔者对RxJS官网基础篇的翻译,如有错漏请指出.本文主要内容:简介和六大概念(Observ

如何理解 RxJS?RxJS的中文API和使用教程

如何理解 RxJS? 我先附上RxJS的中文教程地址方便大家去了解和使用 中文使用教程:http://rxjs-china.org/_book/ 官方中文文档:https://buctwbzs.gitbooks.io/rxjs/content/ 好啦,我们开始讲一下如何理解它 RxJS 可能对很多人而言是一个从没听说过的新名词,那么 RxJS 到底是什么呢?本文中将予以简要介绍 在 Angular 2 中,我们遇到了一个新的概念 —— RxJS. 对很多人而言,这可能是一个比较难以理解的地方.所

[RxJS] Split an RxJS observable conditionally with windowToggle

There are variants of the window operator that allow you to split RxJS observables in different ways. In this lesson we will explore the windowToggle variant and see one of its use cases in user interfaces. Let's say we want to build a new functional

学习RxJS: 导入

引子 新手们在异步编程里跌倒时,永远会有这么一个经典问题:怎么在一次异步调用里return一个结果啊? 老司机说要用回调函数,然后有条件判断的嵌套回调(回调地狱)问题来了: 老司机推荐用事件,然后异步流程里有顺序依赖: 老司机推荐用Promise,然后有顺序依赖的流程里,居然还想订阅事件: 老司机建议试试协程,谁知对方想要合并两个异步调用: -- 以上,是异步编程里要面对的一些难题,也是ReactiveX API 所致力解决的 是什么 知道有 ReactiveX 这么一回事, 源于一位巨硬铁粉的

[RxJS] Add debug method to Observable in TypeScript

Observable.prototype.debug = function(message: any) { return this.do( (next) => { if(!environment.production) { console.log(message, next); } }, (err) => { if(!environment.production) { console.error(message, err) } }, () => { if(!environment.pro

[RxJS] Use groupBy in real RxJS applications

This lesson will show when to apply groupBy in the real world. This RxJS operator is best suited when a source observable represents many data sources, e.g. an observable for multitouch events. const busObservable = Rx.Observable.of( {code: 'en-us',

[RxJS] Flatten a higher order observable with concatAll in RxJS

Besides switch and mergeAll, RxJS also provides concatAll as a flattening operator. In this lesson we will see how concatAll handles concurrent inner Observables and how it is just mergeAll(1). const clickObservable = Rx.Observable .fromEvent(documen