问题描述
在 RxJava 中,有 Observable.OnSubscribe 会调用您的当某物订阅可观察对象时的操作.
In RxJava, there is Observable.OnSubscribe which will call your action when something subscribes to the observable.
在 RxJs 中是否有等价物?
Is there an equivalent in RxJs?
自从提出这个问题后,他们似乎已经撤下了该页面.Google 的缓存版本 住在这里.
推荐答案
通过组合 RxJs5 的现有功能,可以轻松实现该功能.
This function is easily implemented by composition of the existing functions of RxJs5.
Rx.Observable.prototype.doOnSubscribe = function (onSubscribe) {
return Rx.Observable.empty()
.do(null,null, onSubscribe)
.concat(this);
};
Rx.Observable.from([1,2,3])
.doOnSubscribe(() => console.log('subscribed to stream'))
.subscribe(console.log, null, () => console.log('completed'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.3/Rx.js"></script>
当下游订阅 doOnSubscribe
时,我们首先发出一个空的 observable 并使用 .do()
onComplete 回调作为 doOnSubscribe
.然后我们.concat()
上游到这个并返回这个修改后的流.
When downstream subscribes to the doOnSubscribe
we first emit an empty observable and use the .do()
onComplete callback as doOnSubscribe
. Then we .concat()
the upstream to this and return this modified stream.
这篇关于Observable.onSubscribe 等价于 RxJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!