【发布时间】:2017-07-24 22:58:01
【问题描述】:
我正在为 Stomp over Websockets 构建一个小型 RxJS 包装器,它已经可以工作了。
但现在我有了一个非常酷的功能的想法,它可能(希望 - 如果我错了,请纠正我)使用 RxJS 很容易完成。
当前行为:
myStompWrapper.configure("/stomp_endpoint");
myStompWrapper.connect(); // onSuccess: set state to CONNECTED
// state (Observable) can be DISCONNECTED or CONNECTED
var subscription = myStompWrapper.getState()
.filter(state => state == "CONNECTED")
.flatMap(myStompWrapper.subscribeDestination("/foo"))
.subscribe(msg => console.log(msg));
// ... and some time later:
subscription.unsubscribe(); // calls 'unsubscribe' for this stomp destination
myStompWrapper.disconnect(); // disconnects the stomp websocket connection
如您所见,我必须等待state == "CONNECTED" 才能订阅subscribeDestination(..)。否则我会从 Stomp 库中得到一个错误。
新行为:
下一个实现应该让用户更轻松。这是我的想象:
myStompWrapper.configure("/stomp_endpoint");
var subscription = myStompWrapper.subscribeDestination("/foo")
.subscribe(msg => console.log(msg));
// ... and some time later:
subscription.unsubscribe();
它应该如何在内部工作:
-
configure只能在DISCONNECTED时调用 - 当
subscribeDestination被调用时,有两种可能:- 如果
CONNECTED:只需订阅目的地 - 如果
DISCONNECTED:先调用connect(),然后订阅目的地
- 如果
- 当
unsubscribe被调用时,有两种可能:- 如果这是最后一次订阅:致电
disconnect() - 如果这不是最后一次订阅:什么都不做
- 如果这是最后一次订阅:致电
我还不知道怎么去那里,但这就是为什么我在这里问这个问题;-)
提前致谢!
编辑:更多代码、示例和解释
当 configure() 被调用而 not 断开连接时,它应该抛出一个Error。但这没什么大不了的。
stompClient.connect(..) 是非阻塞的。它有一个onSuccess 回调:
public connect() {
stompClient.connect({}, this.onSuccess, this.errorHandler);
}
public onSuccess = () => {
this.state.next(State.CONNECTED);
}
observeDestination(..) 订阅一个 Stomp 消息频道(= 目的地)并返回一个 Rx.Observable,然后可以使用该 Rx.Observable 取消订阅此 Stomp 消息频道:
public observeDestination(destination: string) {
return this.state
.filter(state => state == State.CONNECTED)
.flatMap(_ => Rx.Observable.create(observer => {
let stompSubscription = this.client.subscribe(
destination,
message => observer.next(message),
{}
);
return () => {
stompSubscription.unsubscribe();
}
}));
}
可以这样使用:
myStompWrapper.configure("/stomp_endpoint");
myStompWrapper.connect();
myStompWrapper.observeDestination("/foo")
.subscribe(..);
myStompWrapper.observeDestination("/bar")
.subscribe(..);
现在我想摆脱myStompWrapper.connect()。当第一个通过调用observeDestination(..).subscribe(..) 订阅时,代码应该自动调用this.connect(),当最后一个调用unsubscribe() 时,它应该调用this.disconnect()。
示例:
myStompWrapper.configure("/stomp_endpoint");
let subscription1 = myStompWrapper.observeDestination("/foo")
.subscribe(..); // execute connect(), because this
// is the first subscription
let subscription2 = myStompWrapper.observeDestination("/bar")
.subscribe(..);
subscription2.unsubscribe();
subscription1.unsubscribe(); // execute disconnect(), because this
// was the last subscription
【问题讨论】:
标签: rxjs reactive-programming rxjs5 reactivex reactive