我尝试使用ReactiveUI ReactiveCommands来打开和关闭我已转换为可观察的gRPC流。
下面显示的代码在某种程度上起作用 - 连接按钮将导致流连接,并且我开始在订阅的onNext处理程序中接收数据。断开连接按钮还会通过取消令牌断开流。
但是,一旦执行了disconnect命令,我也希望收到通知,以便我可以清除应用程序中的其他状态。我知道ReactiveCommand的onCompleted永远不会被调用,因为at any point it could be executed again,所以我的问题是 - 我怎么知道流何时被关闭了?
this.WhenActivated(d =>
{
d(this.BindCommand(ViewModel, x => x.ConnectCommand, x => x.Connect));
d(this.BindCommand(ViewModel, x => x.DisconnectCommand, x => x.Disconnect));
});
ConnectCommand = ReactiveCommand.CreateFromObservable(
() => appService.ApplicationStream(request)
.TakeUntil(DisconnectCommand));
ConnectCommand.Subscribe(
resp =>
{
_logger.Debug(resp);
},
() =>
{
// Ideally I could do something useful here, but https://stackoverflow.com/a/26599880/57215
_logger.Debug("Never called, ReactiveCommands never OnComplete");
});
ConnectCommand.IsExecuting.Subscribe(x => _logger.Debug($"is executing: {x}"));
ConnectCommand.CanExecute.Subscribe(x => _logger.Debug($"can execute: {x}"));
ConnectCommand.ThrownExceptions.Subscribe(ex =>
throw new Exception($"Could not get data from server: {ex}"));
DisconnectCommand = ReactiveCommand.Create(
() => { },
ConnectCommand.IsExecuting);
public IObservable<ApplicationStreamResponse> ApplicationStream(ApplicationStreamRequest request)
{
return Observable.Create<ApplicationStreamResponse>(async (observer, token) =>
{
try
{
using (var call = _client.ApplicationStream(request, cancellationToken: token))
{
while (await call.ResponseStream.MoveNext())
{
if (token.IsCancellationRequested) return;
observer.OnNext(call.ResponseStream.Current);
}
observer.OnCompleted();
}
}
catch (RpcException e)
{
if (e.Status.StatusCode == StatusCode.Cancelled)
{
_logger.Debug($"Application stream was disconnected: {e.Status.Detail}");
observer.OnCompleted();
}
observer.OnError(e);
}
});
}
答案 0 :(得分:0)
订阅命令:
d(this.BindCommand(ViewModel, x => x.DisconnectCommand, x => x.Disconnect));
this.ViewModel.DisconnectCommand
.Subscribe(_ => { /* command finished */});
或者创建一个bool reative属性,在DisconnectCommand代码的末尾将其设置为true,并检查视图中的值。