使用 RxJS 在 TypeScript 中创建 BaseObserver

Create BaseObserver in TypeScript using RxJS

我在 Swift 中创建了 BaseObserver,在订阅方法中我传递了这个 class。 我正在尝试使用 TypeScript 在 RxJS 中做同样的事情。

当您想在任何事件发生之前和之后做某事时,这会派上用场。

import Foundation
import RxSwift

class BaseObserver<Element>: ObserverType {

    public typealias E = Element

    var beforeClosure: (() -> Void)?
    var completeClosure: ((E) -> Void)?
    var errorClosure: ((Error) -> Void)?
    var completedClosure: (() -> Void)?
    var alwaysClosure: (()->())?
    var onCompleteOrError: ((Error?) -> Void)?

    init(beforeComplete: (() -> Void)? = nil, onComplete: ((E) -> Void)? = nil, onError: ((Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, always: (()->())? = nil, onCompleteOrError: ((Error?) -> Void)? = nil) {
        self.alwaysClosure = always
        self.completeClosure = onComplete
        self.errorClosure = onError
        self.completedClosure = onCompleted
        self.beforeClosure = beforeComplete
        self.onCompleteOrError = onCompleteOrError
    }

    func on(_ event: Event<Element>) {
        switch event {
        case .next(let element):
            beforeClosure?()
            completeClosure?(element)
        case .error(let error):
            beforeClosure?()
            errorClosure?(error)
            onCompleteOrError?(error)
        case .completed:
            completedClosure?()
            onCompleteOrError?(nil)
        }
        alwaysClosure?()
    }
}
class MyObserver implements Observer<any> {
  constructor(
    private before,
    private after) {
  }

  next = (value: any) => {
    this.before(value)
    this.after(value)
  };
  error = (err: any) => {};
  complete = () => {};
}

const before = value => {
  console.log('before', value)
}
const after = value => {
  console.log('after', value)
}

const observer = new MyObserver(this.before, this.after);

const stream = of(1, 2, 3)
const subscribe = stream.subscribe(this.observer);