如何实现异步订阅?

时间:2017-09-25 14:09:33

标签: c#-4.0 system.reactive

我想为一个observable订阅一个异步方法。这个想法与这里讨论的内容类似:Howto call back async function from rx subscribe?。但我无法更改它,以便我可以将observable(x)携带的值传递给方法。方法D正在工作,看起来像我能接受的东西,但看起来很糟糕。有没有更整洁的方式?

这是基础草图(在LinqPad中):

async Task Main()
{
    var ox = Observable.Interval(TimeSpan.FromSeconds(1)).Timestamp();

    var dA = ox.Subscribe(x => Console.WriteLine("A: {0}: {1}", x.Value, x.Timestamp));

    var dB = ox.Subscribe( _ => AsyncMethod('B',_)); //works, but not awaited
    var dC = ox.Subscribe( async _ => await AsyncMethod('C',_)); //works, but async void, that should be avoided
    var dD = ox.SelectMany( _ => Observable.FromAsync( __ => AsyncMethodD(_))).Subscribe(); // really???

    await Task.Delay(TimeSpan.FromSeconds(10));

    dA.Dispose();
    dB.Dispose();
    dC.Dispose();
    dD.Dispose();
}


async Task AsyncMethod(char mode, Timestamped<long> x)
{
    Console.WriteLine($"{mode}: {x.Value}: {x.Timestamp}");
    await Task.FromResult(true); // fake async
}

async Task AsyncMethodD(Timestamped<long> x)
{
    Console.WriteLine($"D: {x.Value}: {x.Timestamp}");
    await Task.FromResult(true); // fake async
}

谢谢。

0 个答案:

没有答案