组合可观察量



我有两个可观察量:LoadLocal 和 LoadServer。LoadLocal 从本地源加载并返回一个元素,LoadServer 从服务器获取它。我想将它们组合成另一个可观察对象:加载。我希望 Load 从 LoadLocal 获取元素,如果它为 null,我想从 LoadServer 返回元素。关于如何做到这一点的任何想法?

谢谢


真实场景的详细信息:

// loadLocal(id) gives me an observable that returns an asset from a local source
Func<Guid, IObservable<IAsset>> loadLocal = Observable.ToAsync<Guid, IAsset>(id => GetLocalAsset(id));
var svcClient = new ServiceClient<IDataService>();
var svc = Observable.FromAsyncPattern<Request, Response>(svcClient.BeginInvoke, svcClient.EndInvoke);
// calling loadServer(id) gives me an observable that returns an asset from a server
var loadServer = id => from response in svc(new Request(id)) select response.Asset;
// so at this point i can call loadServer(id).Subscribe() to get an asset with specified id from the server, or I can call loadLocal(id).Subscribe() to get it from local source.
// however I want another observable that combines the two so I can do: load(id).Subscribe() that gets the asset from loadLocal(id) and if it is null it gets it from loadServer(id)
var load = ???

下面的几乎给了我想要的结果,但是 loadLocal(id) 和 loadServer(id) 都运行了。如果 loadLocal(id) 返回一个元素,我不希望 loadServer(id) 运行。

var load = id => loadLocal(id).Zip(loadServer(id), (local, server) => local ?? server);

这个怎么样:

loadLocal(id)
    .Where(x => x != null)
    .Concat(Observable.Defer(() => loadServer(id)))
    .Take(1);

也许是这样的东西?

var load = LoadLocal.Zip(LoadServer, (local, server) => local ?? server);

相关内容

  • 没有找到相关文章

最新更新