代码:
subscription = source
// close websocket eventually
.Finally(() => webSocket.CloseAsync(WebSocketCloseStatus.Empty, String.Empty, CancellationToken.None).Wait())
.Subscribe(
data =>
{
if (webSocket.State != WebSocketState.Open)
{
_logger.LogWarning("Websocket closed by client!");
// TODO: End subscription
}
try
{
webSocket.SendAsync(data.ToString(),
WebSocketMessageType.Text, true, CancellationToken.None).Wait();
}
catch (WebSocketException e)
{
_logger.LogWarning(e, "problem with websocket!");
// TODO: End subscription
}
});
说明:
实现这一目标的一种方法是让异常处理不当,这将使观察者停止观察并调用"最后",但问题是它然后崩溃我的整个服务器,因为异常重新抛出一些背景线程并且未处理。
答案 0 :(得分:0)
To end a subscription inside the callback you can just call Dispose()
on the subscription:
IDisposable subscription = null;
...
subscription = source
// close websocket eventually
.Finally(() => webSocket.CloseAsync(WebSocketCloseStatus.Empty, String.Empty, CancellationToken.None).Wait())
.Subscribe(
data =>
{
if (webSocket.State != WebSocketState.Open)
{
_logger.LogWarning("Websocket closed by client!");
subscription.Dispose(); // End subscription
}
try
{
webSocket.SendAsync(data.ToString(),
WebSocketMessageType.Text, true, CancellationToken.None).Wait();
}
catch (WebSocketException e)
{
_logger.LogWarning(e, "problem with websocket!");
subscription.Dispose(); // End subscription
}
});
See also http://www.introtorx.com/content/v1.0.10621.0/03_LifetimeManagement.html#Unsubscribing
答案 1 :(得分:0)
你真的应该尝试像这样定义你的observable:
<h1><?php echo "{$book['title']} by {$book['author']}"; ?></h1>
最终会自动取消订阅。
尽管你可以,但你应该避免在观察者中取消订阅。