How to block ToObservable using list <>?

I am using RX for the first time, and I have a couple of questions.

1) Is there a better way to run Async in my collection?

2) I need to block the thread until all Async tasks are complete, how to do it?

class Program
{

    internal class MyClass
    {
        private readonly List<int> _myData = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        private readonly Random random = new Random();

        public int DoSomething(int j)
        {
            int i = random.Next(j * 1000) - (j * 200);
            i = i < 0 ? 1000 : i;
            Thread.Sleep(i);
            Console.WriteLine(j);
            return j;
        }

        public IObservable<int> DoSomethingAsync(int j)
        {
            return Observable.CreateWithDisposable<int>(
                o => Observable.ToAsync<int, int>(DoSomething)(j).Subscribe(o)
                );
        }

        public void CreateTasks()
        {
            _myData.ToObservable(Scheduler.NewThread).Subscribe(
            onNext: (i) => DoSomethingAsync(i).Subscribe(),
            onCompleted: () => Console.WriteLine("Completed")
                );
        }
    }

    static void Main(string[] args)
    {
        MyClass test = new MyClass();

        test.CreateTasks();

        Console.ReadKey(); 
    } 
}

(Note: I know I could use Observable.Range for my Int list, but my list is not of type Int in a real program).

+3
source share
1 answer

I would probably try

public void CreateTasks()                
{                       
    _myData.ToObservable(Scheduler.NewThread)
        .SelectMany(i => Observable.Start(() => DoSomething(i)))
        .Subscribe(j => Console.WriteLine("j is {0}", j), 
                  () => Console.WriteLine("Completed"));       
} 

So, firstly, I modified DoSomethingAsync so that it uses Observable.Start. Observable.Start starts the method DoSomethingasynchronously and returns a value through IObservable.OnNextwhen the method completes.

CreateTasks , , SelectMany, DoSomethingAsync. OnNext DoSomethingAsync OnComplete, .

+3

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


All Articles