我的目标是从源可观察源创建一组observable,以便我可以单独订阅它们.
当我手动执行此操作(即手动创建每个子源)时,事情按预期工作:添加到原始源的值充分传播到子源.
但是当我在循环中创建它们,将它们添加到a时List<IObservable<T>>,从该列表中获取的元素的订阅似乎不起作用:
class Program
{
static void Main(string[] args)
{
// using Subject for the sake of example
var source = new Subject<int>();
// manually creating each subSource
var source0 = source.Where((t, i) => i % 3 == 0);
var source1 = source.Where((t, i) => i % 3 == 1);
var source2 = source.Where((t, i) => i % 3 == 2);
// creating a List of subsources
List<IObservable<int>> sources = new List<IObservable<int>>();
int count = 3;
for (int i = 0; i < count; i++)
{
sources.Add(source.Where((v, ix) => ix % 3 == i));
}
// subscribing to one subSource from each group
source0.Subscribe(Console.WriteLine); // this works
sources[1].Subscribe(Console.WriteLine); // this doesn't
// feeding data
Observable.Range(0, 20).Subscribe(source);
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
你的Where子句的谓词引用了循环变量i.
但是,在发布值时测试谓词source- 而不是在循环迭代时.到那个时候,i已达到它的最终价值3.
要解决此问题,请在循环内创建一个新变量以存储当前值i,并在Where谓词中引用该变量:
for (int i = 0; i < count; i++)
{
var j = i;
sources.Add(source.Where((v, ix) => ix % 3 == j)); // note use of j here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |