鉴于可观察到的源,通过轮询产生的低级别的设备的状态下的(的变化)...
// observable source metacode:
IObservable<DeviceState> source = Observable.Interval(TimeSpan.FromSeconds(0.5))
.Select(tick => new DeviceState(_device.ReadValue()))
.DistinctUntilChanged();
...和消费者是更新UI ...
// UI metacode:
service.GetObservableDeviceStates()
.Subscribe(state => viewModel.CurrentState = state.ToString());
......我需要执行源的“无为”的x秒后自定义操作,无需中断订阅源。 事情是这样的:
// UI metacode:
service.GetObservableDeviceStates()
.DoOnTimeout(TimeSpan.FromSeconds(x), () => viewModel.CurrentState = "Idle")
.Subscribe(state => viewModel.CurrentState = state.ToString());
什么是最好的做法? 浮现在脑海中可能的解决方案是(我是小白的Rx):
- 缓冲区 (即使它不是那么可读)
- 玩了这个超时超负荷 ;
返回一些特殊的“服务端”时没有什么变化(而不是使用DistinctUntilChanged),并用它的UI代码进行处理:
service.GetObservableDeviceStates().Subscribe(?状态=> viewModel.CurrentState = state.Special “空闲”:state.ToString());
编辑:作为报道的答案 ,解决的办法是:
service.GetObservableDeviceStates()
.Do(onNext)
.Throttle(TimeSpan.FromSeconds(x))
.Subscribe(onTimeout);
EDIT2(警告)
如果onNext和onTimeout更新UI组件,以避免CrossThreadExceptions 2个 ObserveOn(uiSynchronizationContext)都需要,因为油门工作在另一个线程!
service.GetObservableDeviceStates()
.ObserveOn(uiSynchronizationContext)
.Do(onNext)
.Throttle(TimeSpan.FromSeconds(x))
.ObserveOn(uiSynchronizationContext)
.Subscribe(onTimeout);