3

我有两个 observables: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);
4

2 回答 2

2

这个怎么样:

loadLocal(id)
    .Where(x => x != null)
    .Concat(Observable.Defer(() => loadServer(id)))
    .Take(1);
于 2012-04-21T21:49:09.003 回答
1

也许是这样的?

var load = LoadLocal.Zip(LoadServer, (local, server) => local ?? server);
于 2012-04-21T15:54:17.827 回答