如何完成接收观测根据条件在一个活动 [英] How to complete a Rx Observable depending on a condition in a event
问题描述
我有我没有控制哪些为我提供了数据的事件。 EventArgs的看起来是这样的:
类MyEventArg {
布尔IsLastItem {获得;}
数据的DataItem {获得;}
}
我用接收到此事件转换为的IObservable。但是,我要完成的观察到的,如果IsLastItem是真实的。
任何优雅的想法?一种方法是通过管道,我有更多的控制权,如果条件发生时设置的onComplete事件......
如果你想被列入最后一个元素,你只能与最后一个元素连同常规流与 TakeWhile
合并流。
下面是一个简单的控制台应用程序来证明这一点:
无功受=新的List<串>
{
测试,
最后一个
} .ToObservable();
变种我=主题
。凡(X => X ==最后)。以(1)
.Merge(subject.TakeWhile(X => X =最后))!;
my.Subscribe($ B $博=> Console.WriteLine(下一次+ O),
()=> Console.WriteLine(已完成)) ;
到Console.ReadLine();
这将显示:
在下一页:测试
在下一页:最后
已完成
更新
目前是supressed的OnCompleted消息,如果底层的观测实际上并没有完全的错误。我纠正了代码,以确保 OnCompleted
被称为
如果你想避免订阅基础序列多次冷观测量可以重构像这样的代码:
VAR我= subject.Publish(p =指p
。凡(X => X ==最后)采取(1)
.Merge。(p.TakeWhile(X =>!x =最后)));
I have a event that I'm not in control of which provides me with data. The eventArgs looks something like this:
class MyEventArg {
bool IsLastItem {get;}
Data DataItem {get;}
}
I use Rx to convert this event to an IObservable. But I want to complete the observable if IsLastItem is true.
Any elegant ideas? One way would be to pipe the data through a subject that I have more control over to set the OnComplete event if the condition occurs...
If you want the last element to be included you can merge a stream with only the last element together with the regular stream combined with TakeWhile
.
Here is a simple console app to prove it:
var subject = new List<string>
{
"test",
"last"
}.ToObservable();
var my = subject
.Where(x => x == "last").Take(1)
.Merge(subject.TakeWhile(x => x != "last"));
my.Subscribe(
o => Console.WriteLine("On Next: " + o),
() => Console.WriteLine("Completed"));
Console.ReadLine();
This prints:
On Next: test
On Next: last
Completed
UPDATE
There was a bug that supressed the OnCompleted message if the underlying Observable didn't actually complete. I corrected the code to ensure OnCompleted
gets called
And if you want to avoid subscribing to the underlying sequence multiple times for cold observables you can refactor the code like this:
var my = subject.Publish(p => p
.Where(x => x == "last").Take(1)
.Merge(p.TakeWhile(x => x != "last")));
这篇关于如何完成接收观测根据条件在一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!