RXJS:向Observable添加一个函数以在订阅时执行(延迟) [英] RXJS: Adding a function to Observable to execute when subscribed to (defer)

查看:359
本文介绍了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.

这篇关于RXJS:向Observable添加一个函数以在订阅时执行(延迟)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆