How to convert IEnumerable to IObservable?

I want to convert the IEnumerable collection to IObservable without using the Rx ToObservable () and ToEnumerable () methods.

+6
source share
2 answers

The simple answer is to use ToObservable . What is this for.

"Answer the actual question" answer - you can avoid using Subjects through Observable.Create :

 void Main() { var src = Enumerable.Range(0, 10); var observable = Observable.Create<int>(obs => { foreach(var item in src) { obs.OnNext(item); } return Disposable.Create(()=>{}); }); using(observable.Subscribe(Console.WriteLine)) { Console.ReadLine(); } } 

Output:

 0 1 2 3 4 5 6 7 8 9 
+7
source

If you have an IEnumerable unknown type, there are two ways to "convert it to IObservable":

  • Copy all the data into the object into a new collection that implements IObservable . If this is done, only changes made to the new collection will be reported. Changes made to the original will not.

  • Create a new object that will periodically take snapshots of IEnumerable content; after receiving each snapshot, report any changes that must be made to the previous snapshot so that it matches the new one. Using this approach, the changes made to the original object will be observed in the end, but it is difficult to provide timely notification of updates without spending a lot of time re-reading the collection when nothing has changed.

There are several times when you need to bind the IObservable to the original IEnumerable , rather than to a new object that is pre-populated with a copy of the data; in such cases, a second approach may be required. However, it is often impossible to ensure the polling speed fast enough to ensure timely updates without causing an unacceptable system load if the source collection does not support functions that are not available in arbitrary IEnumerable . In addition, if you do not impose requirements on the IEnumerable type, you will most likely have to set restrictions on the thread contexts where they can be updated.

+1
source

Source: https://habr.com/ru/post/946677/


All Articles