在订阅回调中结束订阅

时间:2017-12-16 21:38:11

标签: c# websocket system.reactive reactive-programming

代码:

            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
                        }
                    });

说明:

  • 聆听来自"来源"
  • 的活动
  • 收到的数据 - >发送websocket
  • 异常或websocket closed =>应该终止订阅"来源"并确保websocket已关闭(如果尚未关闭)。如何??

实现这一目标的一种方法是让异常处理不当,这将使观察者停止观察并调用"最后",但问题是它然后崩溃我的整个服务器,因为异常重新抛出一些背景线程并且未处理。

2 个答案:

答案 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>

最终会自动取消订阅。

尽管你可以,但你应该避免在观察者中取消订阅。