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