背景
使用Typescript和RxJS,我试图扩展一个行为主题,以便它将一个observable作为构造参数然后订阅它,以便observable中的每个值都被设置为行为主题的值。 / p>
问题
当行为主体本身至少有一个订阅者时,如何使行为主体仅订阅内部observable?
代码
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
export class SubjectWithInnerObservable<T> extends BehaviorSubject<T> {
constructor(
initialState: any,
someObservable: Observable<T>
) {
super(initialState);
// I only want this subscription to exist when there are one or more subscribers to the behavior subject
someObservable.subscribe(this);
}
}
答案 0 :(得分:1)
您可以在websocket上使用.publishBehavior()
运算符,该运算符内部具有BehaviorSubject。
'发布'位意味着它在连接之前不会发出,就像敲击软管一样。
添加.refCount()
运算符,即可获得订阅时的自动连接,即按订阅计数控制的点按。
文档:RefCount
演示
// mock websocket
const ws = new Rx.Subject()
const autoConnected = ws
.do(x => console.log('ws emits', x)) // just to show ws stream
.publishBehavior(null) // make connectable, i.e only emit when subscribed
.refCount() // auto-connect on subscribe
.filter(x => x) // filter out that pesky initial value
ws.next(1) // before subscription - never emits
const subscription = autoConnected.subscribe(x => console.log('1st subscription', x))
ws.next(2)
ws.next(3)
subscription.unsubscribe()
ws.next(4) // after unsubscribe - never emits
autoConnected.subscribe(x => console.log('2nd subscription', x))
ws.next(5) // after re-subscription - emits last plus next
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>