0

I want to refactor following code:

observable.Subscribe(async i => 
{
   await Task.Yield();
   Console.WriteLine(i);
});

so that I will have second observable, where emitted items are delayed using Task.Yield();

e.g:

var secondObservalbe = observable
   .Delay(e => Task.Yield()); //how to write this

secondObservalbe.Subscribe(i => Console.WriteLine(i));
Liero
  • 25,216
  • 29
  • 151
  • 297
  • The `await Task.Yield()` does not impose a delay. It is sometimes used, [incorrectly IMHO](https://stackoverflow.com/questions/69880987/when-is-it-asynchronous-and-when-is-synchronous/69881887#69881887), with the intention to offload the rest of the method to the `ThreadPool`. If this is your intention, you might want to do it explicitly with the `ObserveOn(ThreadPoolScheduler.Instance)` before subscribing to the sequence. – Theodor Zoulias Dec 10 '21 at 11:00
  • I simply want to defer execution until current event loop iteration is complete. A necessary evil. – Liero Dec 10 '21 at 12:11
  • How about `ObserveOn(Scheduler.CurrentThread)`? – Theodor Zoulias Dec 10 '21 at 12:55
  • `ObserveOn(Scheduler.CurrentThread)` and `ObserveOn(ThreadPoolScheduler.Instance)` is the same, right? It seems legit – Liero Dec 10 '21 at 13:22
  • AFAIK `Scheduler.CurrentThread` means the event loop of the current thread, and `ThreadPoolScheduler.Instance` means a thread from the `ThreadPool`. It's not the same. – Theodor Zoulias Dec 10 '21 at 13:27
  • 1
    Some quick tests in my real app works fine with ObserveOn(Scheduler.CurrentThread), so I will accept that – Liero Dec 10 '21 at 13:42
  • Does `var observable2 = observable.SelectMany(x => Observable.FromAsync(async () => await Task.Yield()).Select(_ => x))` do what you want? – Enigmativity Dec 11 '21 at 07:06
  • 1
    Almost. it gives second level observable, so I had to use some flattening operator, but it seems a little inefficient. It produces YieldAwaitable, transforms that to Task which is then transformed to Observable which much be flattened. – Liero Dec 11 '21 at 07:56

0 Answers0