I am trying on RX for the first time and I have a couple questions.
1) Is there a better way to accomplish the Async of my collection?
2) I need to block on the thread until all Async Tasks are complete, how do I do that?
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 have used Observable.Range for my list of Int but my list is not of type Int in the real program).
I’d probably try
So firstly I’ve changed the DoSomethingAsync so that it uses
Observable.Start. Observable.Start will run theDoSomethingmethod asyncronously and return the value throughIObservable.OnNextwhen the method completes.Then the CreateTasks method runs over each item in the collection as it did before, but feeds each value into a
SelectManywhich continues with a call the DoSomethingAsync method. The result is, that you’ll then recieve anOnNextfor each completed call to DoSomethingAsync and anOnCompletewhen they are all complete.