我想用Rx建模网络连接状态:
我有两个可观察者:
connection
生成有关连接状态更改的true
/ false
通知data
生成要发送的数据的通知虽然connection
已启用(最新值== true
),但我希望data
通知能够立即发送。当connection
发生故障时,我希望来自data
的通知排队,直到它再次上升。
这是所需结果序列的大理石图:
D = down
U = up
connection D U D U
data 1 2 3 4 5 6
result 12 3 456
我找到了一种感觉不正确的解决方案,因为在本地变量(Runnable Gist)中保存状态。
var data = Observable.Interval(TimeSpan.FromSeconds(1));
var connection = new Subject<bool>();
var connected = false;
connection.Do(x => connected = x).Subscribe();
data
.Window(() => connection)
.Subscribe(window =>
{
Console.Write("Starting new window: ");
if (connected == false)
{
Console.WriteLine("Buffering until online");
window
.Buffer(() => connection.Where(x => x))
.Subscribe(buffered => buffered
.ToObservable()
.Subscribe(Console.WriteLine));
}
else
{
Console.WriteLine("Forwarding notifications");
window.Subscribe(Console.WriteLine);
}
});
谢谢!