Rx.Net:链接订户

编程入门 行业动态 更新时间:2024-10-25 07:22:04
本文介绍了Rx.Net:链接订户-替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何重新编写此代码,这样我就不必像下面那样链接订户?询问的原因是,由于代码的样式,这种样式将限制在一个可观察的范围内,这取决于另一个可观察的范围,这可能会造成混淆.

How can I re-write this code so that I don't have to chain Subscribers like below? Reason for asking is, this style will limit in an observable depending on another observable due to the style of the code, it can get confusing.

var results = myService .GetData(accountId) // returns IObservable .Subscribe(data => { new MyWork().Execute(data) // returns IObservable .Subscribe(result => { myResults.Add(result); WriteLine($"Result Id: {result.Id}"); WriteLine($"Result Status: {result.Pass}"); }); });

在彼得·邦斯(Peter Bons)的第一回复之后添加

下面是具有Execute方法的MyWork类的代码

Below is the code for MyWork class that has the Execute Method

public class MyWork { public virtual IObservable<MyResult> Execute(MyData data) { MyResult result = null; return IsMatch(data) .Do(isMatch => { if (isMatch) { result = new MyResult(1, true); } }) .Select(_ => result); } public IObservable<bool> IsMatch(MyData data) { return true; } }

推荐答案

这真的很简单.

var results = myService .GetData(accountId) .SelectMany(data => new MyWork().Execute(data)) .Subscribe(result => { myResults.Add(result); Console.WriteLine($"Result Id: {result.Id}"); Console.WriteLine($"Result Status: {result.Pass}"); });

如果您正在订阅某个订阅,那么您做错了什么.记住这一点.几乎总有一种方法可以使它成为具有单个订阅的纯查询.

If ever you are subscribing within a subscription then you are doing something wrong. Keep that in mind. There is almost always a way to make it a pure query with a single subscription.

只是为了帮助测试,下面是将其设为最小,完整和可验证示例所需的代码. >

Just to help out with testing, here's the code required to make this a Minimal, Complete, and Verifiable example.

public static class myService { public static IObservable<MyData> GetData(int x) => Observable.Return(new MyData()); } public class MyWork { public virtual IObservable<MyResult> Execute(MyData data) { MyResult result = null; return IsMatch(data) .Do(isMatch => { if (isMatch) { result = new MyResult() { Id = 1, Pass = true}; } }) .Select(_ => result); } public IObservable<bool> IsMatch(MyData data) { return Observable.Return(true); } } public class MyResult { public int Id; public bool Pass; } public class MyData { }

更多推荐

Rx.Net:链接订户

本文发布于:2023-11-15 17:26:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1596484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:订户   链接   Rx   Net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!