如何从 ReplaySubject获取最新值完成之前
我需要一种方法来获取添加到 ReplaySubject 中符合特定条件的最新项目。下面的示例代码做了我需要它做的事情,但感觉不是正确的方法:
static void Main(string[] args)
{
var o = new ReplaySubject<string>();
o.OnNext("blueberry");
o.OnNext("chimpanzee");
o.OnNext("abacus");
o.OnNext("banana");
o.OnNext("apple");
o.OnNext("cheese");
var latest = o.Where(i => i.StartsWith("b"))
.Latest().First();
Console.WriteLine(latest);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
输出:
banana
Press any key to exit
最初,我尝试使用 .Where().TakeLast(1)
;但是,我现在从之前的问题中知道您必须在 TakeLast()
返回任何内容之前对主题调用 OnComplete()
。调用 OnComplete()
对我来说不是一个选择,因为我需要保持此流打开。
谁能验证这是否是实现我想要实现的目标的最有效方法?谢谢!
编辑
请注意,我正在使用反应式扩展,并且 IEnumerable 代码示例将不起作用。
更新
我倾向于以下代码,因为我相信它是非阻塞的,除非有人能以不同的方式告诉我:
var latest = o.Where(i => i.StartsWith("b")).Replay(1);
using (latest.Connect())
latest.Subscribe(Console.WriteLine);
I need a way of grabbing the most recent item added to a ReplaySubject that matches certain criteria. The sample code below does what I need it to do but it doesn't feel like the correct approach:
static void Main(string[] args)
{
var o = new ReplaySubject<string>();
o.OnNext("blueberry");
o.OnNext("chimpanzee");
o.OnNext("abacus");
o.OnNext("banana");
o.OnNext("apple");
o.OnNext("cheese");
var latest = o.Where(i => i.StartsWith("b"))
.Latest().First();
Console.WriteLine(latest);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
Output:
banana
Press any key to exit
Initially, I tried using .Where().TakeLast(1)
; however, I now know from a previous question that you must call OnComplete()
on the subject before TakeLast()
will return anything. Calling OnComplete()
is not an option for me because I need to keep this stream open.
Can anyone please validate whether this is the most effective approach to what I'm trying to accomplish? Thanks!
EDIT
Please note that I'm using Reactive Extensions and IEnumerable code samples will not work.
UPDATE
I'm leaning towards the following code because I believe it is non-blocking unless anyone can tell me differently:
var latest = o.Where(i => i.StartsWith("b")).Replay(1);
using (latest.Connect())
latest.Subscribe(Console.WriteLine);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以考虑使用
BehaviorSubject
。缺点是您必须在一开始就订阅,但这可能正是您想要做的。这应该为您提供所需的隔离。输出:
You may consider using
BehaviorSubject<string>
. The drawback is that you have to subscribe at the beginning but that is probably what you want to do anyway. This should provide you with isolation you need.Output:
只要您乐意使用这些阻塞运算符(看起来您就是这样),我就会考虑使用 MostRecent 运算符。
So long as your happy using these blocking operators (which it looks like you are) I'd look into using the MostRecent operator.