我想将列表的 IObservables 存储在一个容器中,并订阅这些 observables 的组合以检索合并的列表。然后我希望能够添加更多的 Observables 而无需续订订阅并仍然获得新的结果。理想情况下,它也应该在将新的 observable 添加到 store 时触发。下面的代码应该解释更多:
using System;
using System.Collections.Generic;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Linq;
namespace dynamic_combine
{
class ObservableStuff
{
private List<IObservable<List<String>>> _listOfObservables = new List<IObservable<List<String>>>();
public ObservableStuff() { }
public void AddObservable(IObservable<List<String>> obs)
{
_listOfObservables.Add(obs);
}
public IObservable<IList<String>> GetCombinedObservable()
{
return Observable.CombineLatest(_listOfObservables)
.Select((all) =>
{
List<String> mergedList = new List<String>();
foreach(var list in all)
{
mergedList = mergedList.Concat(list).ToList();
}
return mergedList;
});
}
}
class Program
{
static void Main(string[] args)
{
ObservableStuff Stuff = new ObservableStuff();
BehaviorSubject<List<String>> A = new BehaviorSubject<List<String>>(new List<String>() { "a", "b", "c" });
BehaviorSubject<List<String>> B = new BehaviorSubject<List<String>>(new List<String>() { "d", "e", "f" });
BehaviorSubject<List<String>> C = new BehaviorSubject<List<String>>(new List<String>() { "x", "y", "z" });
Stuff.AddObservable(A.AsObservable());
Stuff.AddObservable(B.AsObservable());
Stuff.GetCombinedObservable().Subscribe((x) =>
{
Console.WriteLine(String.Join(",", x));
});
// Initial Output: a,b,c,d,e,f
A.OnNext(new List<String>() { "1", "2", "3", "4", "5" });
// Output: 1,2,3,4,5,d,e,f
B.OnNext(new List<String>() { "6", "7", "8", "9", "0" });
// Output: 1,2,3,4,5,6,7,8,9,0
Stuff.AddObservable(C.AsObservable());
// Wishful Output: 1,2,3,4,5,6,7,8,9,0,x,y,z
C.OnNext(new List<String>() { "y", "e", "a", "h" });
// Wishful Output: 1,2,3,4,5,6,7,8,9,0,y,e,a,h
Console.WriteLine("Press the any key...");
Console.ReadKey();
}
}
}
虽然示例是用 C# 编写的,但它最终需要在 rxCpp 中实现。此外,在其他 Rx 变体中看到实现也会很有趣。
我已经设置了一个存储库来检查代码,并且可能会将其扩展到其他语言: https ://gitlab.com/dwaldorf/rx-examples
BR,丹尼尔