为什么热可观察重新订阅
Why hot observable resubscribe
我有一个监听 table select 事件的 observable,它也很热。
代码片段:
const oTableRowSelect$ = TableOb.rowSelectionChangeEvent$(this.getById("ins-table"));
const test = oTableRowSelect$
.do(function () {
console.log("resubscribe");
})
.map(function () {
return 4;
});
test.subscribe(function (o) {
console.log("Select1" + o);
});
test.subscribe(function (o) {
console.log("Select2" + o)
});
如您所见,有两个订阅者在监听事件。所以结果应该分享给所有订阅者,这就是所谓的重播效果。
我得到的输出是:
但我希望 resubscribe
只输出一次。我做错了什么?
虽然您的 oTableRowSelect$
可能 热门 并已共享,但它仅共享您通过其他操作员以某种方式扩展它的部分(在您的案例 do
和 map
).
在 RxJS 中,任何通过运算符的扩展基本上都会 return 一个 "new" 流。
为了使这个 "new" 流 hot/shared 你必须应用一个使它变热的运算符 (share
, publish
, publishReplay
, 等...)
const hotBaseStream$ = new Rx.BehaviorSubject("Hi!");
const test = hotBaseStream$
// -------- below this line you get a "new" stream, that is not hot any more
.do(() => console.log("resubscribe"))
.map(() => 4)
.publishReplay().refCount(); // remove this part and you will have back your original behavior
test.subscribe(function (o) {
console.log("Select1 ", o);
});
test.subscribe(function (o) {
console.log("Select2 ", o)
});
<script src="https://unpkg.com/@reactivex/rxjs/dist/global/Rx.js"></script>
我有一个监听 table select 事件的 observable,它也很热。
代码片段:
const oTableRowSelect$ = TableOb.rowSelectionChangeEvent$(this.getById("ins-table"));
const test = oTableRowSelect$
.do(function () {
console.log("resubscribe");
})
.map(function () {
return 4;
});
test.subscribe(function (o) {
console.log("Select1" + o);
});
test.subscribe(function (o) {
console.log("Select2" + o)
});
如您所见,有两个订阅者在监听事件。所以结果应该分享给所有订阅者,这就是所谓的重播效果。
我得到的输出是:
但我希望 resubscribe
只输出一次。我做错了什么?
虽然您的 oTableRowSelect$
可能 热门 并已共享,但它仅共享您通过其他操作员以某种方式扩展它的部分(在您的案例 do
和 map
).
在 RxJS 中,任何通过运算符的扩展基本上都会 return 一个 "new" 流。
为了使这个 "new" 流 hot/shared 你必须应用一个使它变热的运算符 (share
, publish
, publishReplay
, 等...)
const hotBaseStream$ = new Rx.BehaviorSubject("Hi!");
const test = hotBaseStream$
// -------- below this line you get a "new" stream, that is not hot any more
.do(() => console.log("resubscribe"))
.map(() => 4)
.publishReplay().refCount(); // remove this part and you will have back your original behavior
test.subscribe(function (o) {
console.log("Select1 ", o);
});
test.subscribe(function (o) {
console.log("Select2 ", o)
});
<script src="https://unpkg.com/@reactivex/rxjs/dist/global/Rx.js"></script>