neuecc / UniRx

Reactive Extensions for Unity
MIT License
7.08k stars 892 forks source link

Although scheduling on MainThread still getting error that API accessed from other thread. #261

Open Zammy opened 6 years ago

Zammy commented 6 years ago

I am getting this error

SetString can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. UnityEditor.EditorPrefs:SetString(String, String)

        Observable.ReturnUnit()
            .SubscribeOn(Scheduler.ThreadPool)
            .Select(_ => {Debug.Log("Print!"); return Unit.Default;})
            .SubscribeOn(Scheduler.MainThread)
            .Subscribe(_ => EditorPrefs.SetString("key", "data"));

What am I doing wrong?

This is executed inside EditorWindow.

Lailore commented 6 years ago

You need use ObserveOnMainThread. Not SubscribeOn. https://stackoverflow.com/questions/20451939/observeon-and-subscribeon-where-the-work-is-being-done