neuecc / UniRx

Reactive Extensions for Unity
MIT License
7.01k stars 895 forks source link

ObserveOnMainThread does not propagate events from background threads to main thread #519

Open nikomikulicic opened 1 year ago

nikomikulicic commented 1 year ago

It's weird. Here's a sample code:

private void TakeAITurnsAsync(Action onComplete)
{
        Debug.Log("AI Take AI turns started. Thread: " + System.Threading.Thread.CurrentThread.Name);

        aiTurnSubscription = Observable
            .Start(() => 
            { 
                System.Threading.Thread.Sleep(millisecondsTimeout: 1000));
                Debug.Log("AI Take AI turns completed. Thread: " + System.Threading.Thread.CurrentThread.Name);
            })
            .Do(
                onNext: _ => Debug.Log("AI BG onNext. Thread: " + System.Threading.Thread.CurrentThread.Name),
                onError: _ => Debug.Log("AI BG onError. Thread: " + System.Threading.Thread.CurrentThread.Name),
                onCompleted: () => Debug.Log("AI BG onComplete. Thread: " + System.Threading.Thread.CurrentThread.Name)
            )
            .ObserveOnMainThread()
            .Do(
                onNext: _ => Debug.Log("AI MAIN onNext. Thread: " + System.Threading.Thread.CurrentThread.Name),
                onError: _ => Debug.Log("AI MAIN onError. Thread: " + System.Threading.Thread.CurrentThread.Name),
                onCompleted: () => Debug.Log("AI MAIN onComplete. Thread: " + System.Threading.Thread.CurrentThread.Name)
            )
            .Subscribe(_ =>
            {
                onComplete?.Invoke();
            });
}

Output:

AI Take AI turns started. Thread: 
AI Take AI turns completed. Thread: Thread Pool Worker
AI BG onNext. Thread: Thread Pool Worker
AI BG onComplete. Thread: Thread Pool Worker

AI MAIN onNext text is never in output and onComplete?.Invoke(); line is never called. Since background thread does emit onNext and onCompleted events, I would expected that the same would be emitted on main thread when using ObserveOnMainThread. What did I do wrong?