我有两个observable: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);
答案 0 :(得分:2)
这个怎么样:
loadLocal(id)
.Where(x => x != null)
.Concat(Observable.Defer(() => loadServer(id)))
.Take(1);
答案 1 :(得分:1)
也许是这样的东西?
var load = LoadLocal.Zip(LoadServer, (local, server) => local ?? server);