RXJS:向Observable添加一个函数,以便在订阅时执行(延迟)

时间:2017-10-23 03:24:06

标签: typescript bluetooth rxjs observable ionic3

向Observable添加一个函数,以便在订阅(延迟)

时执行

我有一个由事件制成的Observable。在这种情况下,蓝牙通知。

我只想在有人订阅Observable时运行一个函数(startNotifictions)。

此代码在以前的版本中确实有效。它与Ionic3框架有关。它添加了一个新的运算符,在订阅时运行。现在,转换器有类型的问题,抱怨两次,.doOnSubscribe在typedef Observable上不可用任何>和< {}>。

任何人都知道如何正确输入该类型?可能延长? 试图直接使用.defer,无济于事。



 // add operator doOnSubscribe to the event observable
        Observable.prototype.doOnSubscribe = function(onSubscribe) {
            let source = this;
            return Observable.defer(() => {
                onSubscribe();
                return source;
            });
        };

        // return the Observable for the notify char, with startNotify on first subscribe
        getUartDataNote( Observable.fromEvent( this.uartChar, 'characteristicvaluechanged' )
            .doOnSubscribe(() => {
                console.log('starting note');
                this.uartChar.startNotifications();
            })
            .map( value => String.fromCharCode.apply( null, new Uint8Array( this.uartChar.value.buffer )))
            .takeUntil( Observable.fromEvent( this.gatt.device, 'gattserverdisconnected' ))
            .finally(() => {
                console.log( 'stream disconnected ');
                // not necessary: return this.uartChar.stopNotifications()
            })
            .share()
        );




1 个答案:

答案 0 :(得分:2)

以下是编写类型扩充的方法。

export {}

declare module 'rxjs/Observable' {
  interface Observable<T> {
    doOnSubscribe(onSubscribe: () => void): this;
  }
}

这是在TypeScript手册的Declaration Merging部分中记录的。

相关问题