Observable.Using with async Task

时间:2017-09-27 08:20:56

标签: c# .net observable system.reactive

我已经使用了Observable.Using和方法返回IDisposable:

Observable.Using(() => new Stream(), s => DoSomething(s));

但是,当异步创建流时,我们将如何进行?就像这样:

Observable.Using(async () => await CreateStream(), s => DoSomething(s));

async Task<Stream> CreateStream() 
{
    ...
}

DoSomething(Stream s)
{
    ...
}

这不会编译,因为它说sTask<Stream>而不是Stream

这笔交易是什么?

1 个答案:

答案 0 :(得分:2)

让我们看一下Observable.Using

的异步重载的来源
Observable.FromAsync(resourceFactoryAsync)
    .SelectMany(resource => Observable.Using(() => resource, r =>
        Observable.FromAsync(ct => observableFactoryAsync(r, ct)).Merge()));

知道它只是使用同步版本,你可以做这样的事情来适应你的使用:

Observable.FromAsync(CreateStream)
    .SelectMany(stream => Observable.Using(() => stream, DoSomething));

不幸的是,不包括过载,但您可以随时创建自己的:

public static class ObservableEx
{
    public static IObservable<TSource> Using<TSource, TResource>(
        Func<Task<TResource>> resourceFactoryAsync,
        Func<TResource, IObservable<TSource>> observableFactory)
        where TResource : IDisposable =>
        Observable.FromAsync(resourceFactoryAsync).SelectMany(
            resource => Observable.Using(() => resource, observableFactory));
}

然后它就像:

一样简单
ObservableEx.Using(CreateStream, DoSomething);

所有这一切都假设DoSomething返回一个observable,在你的问题中没有提到,但是Observable.Using的合同要求。{/ p>