gpt4 book ai didi

c# - 结合观察

转载 作者:行者123 更新时间:2023-11-30 16:25:02 25 4
gpt4 key购买 nike

我有两个可观察对象:LoadLocal 和 LoadServer。 LoadLocal 从本地源加载并返回一个元素,而 LoadServer 从服务器获取它。我想将它们组合成另一个可观察对象:Load。我想让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);

关于c# - 结合观察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10260525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com