如何在TypeScript中创建扩展Rx.Observable的类?

时间:2015-05-27 23:16:15

标签: typescript rxjs

我已经使用了最新版本的rx.js从Definitely Typed打字。

当我尝试这个时:

class MyObservable extends Rx.Observable<any> { }

我得到了:A class may only extend another class.

为什么ObservableSubject等被定义为rx.d.ts中类的接口instand?

如果我想创建一个扩展Observable或Subject的类,我该怎么办?

P.S。我希望这个类处理特定的域逻辑,所以我需要创建一个新类,而不是直接更新Observable的原型。

谢谢!

2 个答案:

答案 0 :(得分:5)

我必须为WebRx解决同样的问题。正如您已经发现的那样,使用Typescript类扩展RxJS的IObservable不是一个选项,因为Observable被导出为接口。正如我在Steve Fenton的回答中所提到的那样,创建一个实现Rx.IObservable的类不会让你走得太远,因为绝大多数Rx运算符是围绕Rx定义的。从Rx.IObservable派生的可观察接口。你几乎最终会重写Rx.Observable。

我解决这个问题的方法是,使用prototypal inheritance扩展内置的Rx.Observable并通过custom d.ts文件导出扩展名更好的方法:

<强> RxExtension.ts

var RxObsConstructor = (<any> Rx.Observable);   // this hack is neccessary because the .d.ts for RxJs declares Observable as an interface)

/**
* Creates an read-only observable property with an optional default value from the current (this) observable
* (Note: This is the equivalent to Knockout's ko.computed)
* @param {T} initialValue? Optional initial value, valid until the observable produces a value
*/
RxObsConstructor.prototype.toProperty = function(initialValue?: any, scheduler?: Rx.IScheduler) {
    scheduler = scheduler || Rx.Scheduler.currentThread;

    // initialize accessor function (read-only)
    var accessor: any = (newVal?: any): any => {
        if (arguments.length > 0) {
            internal.throwError("attempt to write to a read-only observable property");
        }

        if (accessor.sub == null) {
            accessor.sub = accessor._source.connect();
        }

        return accessor.value;
    };

    //////////////////////////////////
    // IUnknown implementation

    accessor.queryInterface = (iid: string) => {
        if (iid === IID.IUnknown ||
            iid === IID.IObservableProperty ||
            iid === IID.IDisposable)
            return true;

        return false;
    };

    //////////////////////////////////
    // IDisposable implementation

    accessor.dispose = () => {
        if (accessor.sub) {
            accessor.sub.dispose();
            accessor.sub = null;
        }
    };

    //////////////////////////////////
    // IObservableProperty<T> implementation

    accessor.value = initialValue;

    // setup observables
    accessor.changedSubject = new Rx.Subject<any>();
    accessor.changed = accessor.changedSubject
        .publish()
        .refCount();

    accessor.changingSubject = new Rx.Subject<any>();
    accessor.changing = accessor.changingSubject
        .publish()
        .refCount();

    accessor.source = this;
    accessor.thrownExceptions = internal.createScheduledSubject<Error>(scheduler, app.defaultExceptionHandler);

    //////////////////////////////////
    // implementation

    var firedInitial = false;

    accessor.sub = this
        .distinctUntilChanged()
        .subscribe(x => {
            // Suppress a non-change between initialValue and the first value
            // from a Subscribe
            if (firedInitial && x === accessor.value) {
                return;
            }

            firedInitial = true;

            accessor.changingSubject.onNext(x);
            accessor.value = x;
            accessor.changedSubject.onNext(x);
        }, x=> accessor.thrownExceptions.onNext(x));

    return accessor;
}

<强> RxExtension.d.ts

declare module Rx {
    export interface Observable<T> extends IObservable<T> {
        toProperty(initialValue?: T): wx.IObservableProperty<T>;
    }
}

答案 1 :(得分:0)

rx.js中的基础Observable无法扩展,因为它更像是TypeScript module,而不是class(即它是单身)。

 var Observable = Rx.Observable = (function () {
     //...
 })();

这就是它在Definitely Typed定义中被建模为接口而不是类的原因。要实现接口,必须提供与接口兼容的结构。以下是IObservable<T>的示例。

class MyObservable<T> implements Rx.IObservable<T> {
    subscribe(observer: Rx.Observer<T>): Rx.IDisposable;
    subscribe(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Rx.IDisposable;
    subscribe(a?: Rx.IObserver<T> | Function, onError?: (exception: any) => void, onCompleted?: () => void) {
        return null;
    }

    subscribeOnNext(onNext: (value: T) => void, thisArg?: any): Rx.IDisposable {
        return null;
    }

    subscribeOnError(onError: (exception: any) => void, thisArg?: any): Rx.IDisposable {
        return null;
    }

    subscribeOnCompleted(onCompleted: () => void, thisArg?: any): Rx.IDisposable {
        return null;
    }
}