简体   繁体   English

可观察序列Rx c#的多个订阅

[英]Multiple subscriptions to Observable sequence Rx c#

I am trying to learn Rx framework in .NET and in the process of applying it one of the tasks that I am working on. 我正在尝试在.NET中学习Rx框架,并在应用它的过程中学习我正在从事的任务之一。 The functionality that I am trying is explained in this simple use case below. 我在下面的这个简单用例中说明了我正在尝试的功能。

I have a sequence of IEnumerable which I need to process in parallel and apply a function( async function ) to it which returns an int. 我有一个IEnumerable序列,需要并行处理并向其应用一个函数(异步函数),该函数返回一个int值。 based on the value returned. 根据返回的值。 In the code below the new sequences oddSequence and evenSequence are created only after the original "sequence" is created, so there is not real "fire and forget" happening here. 在下面的代码中,仅在创建原始“序列”之后才创建奇怪序列和evenSequence,因此这里没有发生真正的“即发即弃”。 What is correct way to approach this problem using Rx? 使用Rx解决此问题的正确方法是什么?

    public void TestRx()
    {
        IEnumerable<string> inputs = new string[] { "T-1", "T-2", "T-3"};

        var sequence = inputs.ToObservable().Select(x => ReturnResult(x)).Merge();

        var oddSequence = sequence.Where(x => (x%2) != 0);
        var evenSequence = sequence.Where(x => (x%2) == 0);

        oddSequence.Subscribe(i => Console.WriteLine($"ODD VALUE {i}"));
        evenSequence.Subscribe(i => Console.WriteLine($"EVEN VALUE {i}"));
    }

    public async Task<int> ReturnResult(string s)
    {
        int result = -1;
        Int32.TryParse(s.Split('-')[1], out result);
        return result;
    }

Thank you helping me out 谢谢你帮我

This will do the job: 这将完成工作:

private Random random = new Random();

public void TextRx()
{
    new[] {"T-1", "T-2", "T-3"}
        .Select(s => ReturnResult(s).ToObservable())
        .Merge()
        .GroupBy(i => i % 2 == 0)
        .SelectMany(g => g.Select(i => (g.Key, Value: i)))
        .Subscribe(o => Console.WriteLine($"{(o.Key ? "EVEN" : "ODD")} VALUE {o.Value}"));
}

public async Task<int> ReturnResult(string s)
{
    await Task.Delay(random.Next(5000));
    int.TryParse(s.Split('-')[1], out var result);
    return result;
}
  • It uses ValueTuple , which is a C# 7 feature. 它使用ValueTuple ,这是C#7的功能。 You'd need to grab it with Nuget. 您需要使用Nuget抓住它。 Of course you could use an anonymous object, but I prefer ValueTuple . 当然,您可以使用匿名对象,但我更喜欢ValueTuple It's also using out variables from C#7 and string interpolation from C# 6. 它还使用C#7中的out变量和C#6中的字符串插值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM