简单模拟实现Rxjs Observable

技术分享4年前 (2020)更新 技术分享
2,374 0 0

1.先定义类型

export type Observer = {
    next: (any) => void,
    complete?: (any) => void,
}

export interface OnSubscribeAction {
    (observer: Observer): void;
}

 export interface mapFun {       (x: any): any   }

 

2.自定义类

export class MyObservable {
    private subscribeAction: OnSubscribeAction;
    constructor(subscribeAction: OnSubscribeAction) {
        this.subscribeAction = subscribeAction;
    }

    subscribe(observer: Observer) {
        return this.subscribeAction(observer)
    }
}

3.实例

const onSubscribe: OnSubscribeAction = (observer: Observer) => {
      observer.next(1);
      observer.next(2);
      observer.next(3);
}

const theObserver = {
   next: console.log,
}

const source$ =  new MyObservable(onSubscribe);
source$.subscribe(theObserver);

结果一次输出1,2,3

 

4.增加map操作符

export class MyObservable {
    private subscribeAction: OnSubscribeAction;
    constructor(subscribeAction: OnSubscribeAction) {
        this.subscribeAction = subscribeAction;
    }

    subscribe(observer: Observer) {
        return this.subscribeAction(observer)
    }
  //rxjs 的每个操作符都会返回一个新的Observable
    map(fun: mapFun) {
         const nextObserver =  new MyObservable((observer: Observer) => {
            this.subscribe({
                next(item){
                    observer.next(fun(item))
                }
            })
         })
         return nextObserver
    }
}

5.

const onSubscribe: OnSubscribeAction = (observer: Observer) => {
      observer.next(1);
      observer.next(2);
      observer.next(3);
    }

    const theObserver = {
      next: console.log,
    }

    const source$ =  MyObservable.create(onSubscribe);
    source$.map(x => x * 2).map(x => x + 1).subscribe(theObserver);

结果一次输出3,5,7

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...