這一切都取決於您的操作順序。
如果你組織你的代碼是這樣的:
List<int> intList = new List<int>() { 1, 2, 3 };
IObservable<int> observableList = intList.ToObservable();
intList.Add(4);
IDisposable subscription =
observableList
.Subscribe(
x => Console.WriteLine("Received {0} from source.", x),
ex => Console.WriteLine("OnError: " + ex.Message),
() => Console.WriteLine("OnCompleted"));
...那麼它可以作爲你的期望。
問題是.Subscribe
在.ToObservable()
的當前線程上運行。實際的代碼運行是return (IObservable<TSource>) new ToObservable<TSource>(source, SchedulerDefaults.Iteration);
。 SchedulerDefaults.Iteration
是當前線程。
你可以用這個代碼裏發現:
List<int> intList = new List<int>() { 1, 2, 3 };
IObservable<int> observableList = intList.ToObservable();
Console.WriteLine("Before Subscription");
IDisposable subscription =
observableList
.Subscribe(
x => Console.WriteLine("Received {0} from source.", x),
ex => Console.WriteLine("OnError: " + ex.Message),
() => Console.WriteLine("OnCompleted"));
Console.WriteLine("After Subscription, Before Add");
intList.Add(4);
Console.WriteLine("After Add");
當我運行它,我得到:
Before Subscription
Received 1 from source.
Received 2 from source.
Received 3 from source.
OnCompleted
After Subscription, Before Add
After Add
所以.Add
甚至還沒有發生,直到後認購完成。
現在,如果我試圖通過將代碼更改爲intList.ToObservable(Scheduler.Default)
來解決此問題,那麼我會遇到一個新問題。運行我的上面的代碼我得到這個:
Before Subscription
After Subscription, Before Add
After Add
Received 1 from source.
OnError: Collection was modified; enumeration operation may not execute.
現在很明顯,我們有一個併發問題。您不應該嘗試操作集合並同時迭代它們。
你應該看看[dynamic-data](http://dynamic-data.org/)。 – Dorus