Inside a platform, Android or iOS, which Rx Scheduler should be used to ObserveOn the Main Thread?

Viewed 913

When using Rx.NET in a platform specific project

  • Android
  • iOS

How do you ObserveOn the main thread? It doesn't look like ObserveOnDispatcher() is available under iOS or Android when using Xamarin.

This sample does work, as I know I am on the main thread when I subscribe. I just didn't know if there was a more formal way to deal with: "ALWAYS" use the main thread even if I am not on the main thread.

myObservable // assume this does work on an alternate thread
.ObserveOn(SynchronizationContext.Current)
.Subscribe(OnMyObservableNext);

Again, if I am on the main thread, say in a click event handler, I know that using SynchronizationContext.Current will put me back onto that thread. In testing this I have verified that as well.

What I am looking for though is the case where I may not be on the main thread and I want to get back there (from a PCL).

I can think of a solution where I store the SynchronizationContext.Current on a static class, in the case of iOS, in the FinishedLaunching method of the App Delegate. I don't know if this is advisable or not.

The solution mentioned above would be something like this:

PCL

namespace MyPCL
{

    public static class Settings
    {
        // obvioulsy probably don't want public setter, 
        // don't want anyone reaching in here and changiing it
        // from under us. But for the example this is fine.
        public static SynchronizationContext MainContext { get; set; }
    }
}

iOS

using MyPCL;

namespace MyApp.iOS
{
    [Register ("AppDelegate")]
    public class AppDelegate : UIApplicationDelegate
    {
        public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
        {
            // ...
            Settings.MainContext = SynchronizationContext.Current;
            // ^^^^ Save the Main SynchronizationContext 
            // ...
            return true;
        }
    }
}
1 Answers
Related