简单模拟实现Rxjs Observable

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

上一篇:openssl编译(VC6.0)


下一篇:spring-data-redis和jedis版本对应收集总结