[RxJS] Creation operator: create()

本文详细介绍了RxJS中Observable的创建方法,通过示例代码解释了如何使用create()函数及new Rx.Observable()来实例化Observable对象,并展示了这些方法的具体工作原理。

We have been using Observable.create() a lot in previous lessons, so let's take a closer look how does it work.

 

The create function:

var foo = Rx.Observable.create( function(observer){
  observer.next(42);
  observer.next(100);
  observer.next(200);
  observer.complete();
})  ;

foo.subscribe( 
  (x)=>{console.log('next ' + x);},
  (err)=>{console.log('err ' + err);},
  ()=>{console.log('done');},
)

 

In deep, create() function equal to new Rx.Observable():

var foo = new Rx.Observable( function(observer){
  observer.next(42);
  observer.next(100);
  observer.next(200);
  observer.complete();
})  ;

And this also equal to:

function subscribe(observer){
  observer.next(42);
  observer.next(100);
  observer.next(200);
  observer.complete();
}
  
var foo = new Rx.Observable( subscribe );

 

So, if we get rid of RxJS, then we can create the create() function like:

function subscribe(observer){
  observer.next(42);
  observer.next(100);
  observer.next(200);
  observer.complete();
}

var observer = {
  next: (x)=>{console.log('next ' + x);},
  error: (err)=>{console.log('err ' + err);},
  complete: ()=>{console.log('done');}
}


subscribe(observer);

Of course, it's useful to have the observable type because then it has all those nice operators that we saw and that we are also seeing new operators coming next. If you paid attention, then you're going to remember that in the subscribe, we had previously three functions here as argument. Instead of an object, as we have now, we had just these three functions.

Also, the observable type, it converts these three functions into an observer object. Before it calls this, it will actually take these three functions and put labels in front of them like that, to create the observer object. It's normalizing it.

转载于:https://www.cnblogs.com/Answer1215/p/5401422.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值