RXJS:向Observable添加一个函数以在订阅时执行(延迟)
我有一个来自事件的Observable.在这种情况下,将发出蓝牙通知.
I have an Observable made from events. In this case, Bluetooth notifications.
我只想在有人订阅该Observable时运行一个函数(startNotifictions).
I want to run a function (startNotifictions) only when someone is subscribing to that Observable.
此代码在以前的版本中确实有效.它与Ionic3框架一起使用.它添加了一个新的运算符,该运算符在订阅时运行.现在,编译器遇到类型问题,两次抱怨说,.doOnSubscribe在typedef上不可用.和< {}>.
This code did work, on previous versions. It is with Ionic3 framework. It added a new operator, that ran when subscribed. Now the transpiler has a problem with the types, complaining twice, that the .doOnSubscribe is not available on typedef Observable any> and <{}>.
任何人都有一个想法如何正确输入?延长也许? 尝试直接使用.defer,无济于事.
Anyone has an idea how to get that typed correctly? Extend maybe? Tried to use .defer directly, no avail.
// 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()
);
这是您编写类型扩充的方式.
Here is how you write the type augmentation.
export {}
declare module 'rxjs/Observable' {
interface Observable<T> {
doOnSubscribe(onSubscribe: () => void): this;
}
}
声明合并 TypeScript手册的部分.
This is documented in the Declaration Merging section of the TypeScript handbook.