[英]How to combine IObservable sequences in UniRx/Rx.NET?
I'm using the UniRx flavor of Reactive Extensions for the Unity3D game engine.我正在为 Unity3D 游戏引擎使用反应式扩展的 UniRx 风格。 Unity uses C#, so I guess it's similar to Rx.NET.
Unity使用的是C#,所以我猜它类似于Rx.NET。
I need a more beautiful way of checking when several observable sequences complete.我需要一种更漂亮的方法来检查几个可观察序列何时完成。
In the example below, one of the sequences is dependent on the outcome of the first (since it needs an integer for processID
).在下面的示例中,其中一个序列取决于第一个序列的结果(因为它需要一个 integer 用于
processID
)。
The observables are both of type IObservable<string>
. observables 都是
IObservable<string>
类型。
var processListObservable = APIBuilder
.GetProcessList(authInfo.Token, authInfo.PlatformURL, (int)product.Id)
.Subscribe(listJson =>
{
processList = ProcessList.FromJson(listJson);
int processID = (int)processList.Processes[0].ProcessDataId;
//Retrieve Detailed information of the first entry
var processDetailsObservable = APIBuilder
.GetProcessDetails(token, platformURL, product.Id, processID)
.Subscribe(detailsJson =>
{
processData = ProcessData.FromJson(detailsJson);
SetupPlotView();
});
});
Any hint would be highly appreciated.任何提示将不胜感激。 Also some suggestions to solve the same scenario minus the dependency on the result of the first sequence.
还有一些解决相同场景的建议减去对第一个序列结果的依赖。
Instead of putting your code into the Subscribe
handler, you could make it part of the sequence.您可以将其作为序列的一部分,而不是将您的代码放入
Subscribe
处理程序中。 You could use the Select
operator in order to project each listJson
to an IObservable<string>
(resulting to a nested IObservable<IObservable<string>>
), and then flatten the sequence by using either the Concat
or the Merge
operator, depending on whether you want to prevent or allow concurrency.您可以使用
Select
运算符将每个listJson
到IObservable<string>
(导致嵌套的IObservable<IObservable<string>>
),然后使用Concat
或Merge
运算符展平序列,具体取决于是否您想阻止或允许并发。
var processListObservable = APIBuilder
.GetProcessList(authInfo.Token, authInfo.PlatformURL, (int)product.Id)
.Select(listJson =>
{
var processList = ProcessList.FromJson(listJson);
int processID = (int)processList.Processes[0].ProcessDataId;
return APIBuilder.GetProcessDetails(token, platformURL, product.Id, processID);
})
.Concat() // or .Merge() to allow concurrency
.ObserveOn(SynchronizationContext.Current) // Optional
.Do(detailsJson =>
{
var processData = ProcessData.FromJson(detailsJson);
SetupPlotView(processData);
});
await processListObservable.DefaultIfEmpty(); // Start and await the operation
The await
in the final line will cause an implicit subscription to the processListObservable
, and your code will execute as a side-effect of this subscription.最后一行中的
await
将导致对processListObservable
的隐式订阅,并且您的代码将作为此订阅的副作用执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.