[RxJS] Use `lift` to Connect a `source` to a `subscriber` in RxJS

The lift method on each source hides away the internals of RxJS so you can simply connect a source to the subscriber you're working with. The lift method take an object with a call function with subscriber and source arguments, then it's up to you how you want to connect them together.

 

Previous we created a custom subscriber, we do it in subscribe() function:

import { from, Subscriber } from "rxjs";

const observable$ = from([1, 2, 3, 4, 5]);

const subscriber = {
  next: value => {
    console.log(value);
  },
  complete: () => {
    console.log("done");
  },
  error: value => {
    console.log(value);
  }
};

class DoulbeSubscriber extends Subscriber {
  _next(value) {
    this.destination.next(value * 2);
  }
}

observable$.subscribe(new DoulbeSubscriber(subscriber));

 

Of course it isn't ideal to do the transformation in subscriber.

Better way is that we can do though `pipe`, create a custom subscriber and using in the pipe:

const doulbe = source => {
  return source.lift({
    call(sub, source) {
      source.subscribe(new DoulbeSubscriber(sub));
    }
  });
};

observable$.pipe(doulbe).subscribe(subscriber);

 

We can use `lift` function which accpet an object has a call(subscriber, source).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值