Skip to content

Commit ce9c29a

Browse files
committed
Fix AndroidSchedulers to create an instance using hook only once.
Previously we were asking the hook for an instance every time `mainThread()` was called. This not only impacted performance, but also broke the contract the that hook was a factory–instead requiring that it behave like a thread-safe, lazily-initialized instance cache. If for whatever reason you do need to change the instance over time, return a scheduler instance which delegates to another and allows swapping out the delegate.
1 parent aeb3ae5 commit ce9c29a

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

rxandroid/src/main/java/rx/android/schedulers/AndroidSchedulers.java

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,28 @@
1616
import android.os.Looper;
1717
import rx.Scheduler;
1818
import rx.android.plugins.RxAndroidPlugins;
19+
import rx.android.plugins.RxAndroidSchedulersHook;
1920

2021
/** Android-specific Schedulers. */
2122
public final class AndroidSchedulers {
23+
private static final AndroidSchedulers INSTANCE = new AndroidSchedulers();
24+
25+
private final Scheduler mainThreadScheduler;
26+
2227
private AndroidSchedulers() {
23-
throw new AssertionError("No instances");
24-
}
28+
RxAndroidSchedulersHook hook = RxAndroidPlugins.getInstance().getSchedulersHook();
2529

26-
// See https://github.com/ReactiveX/RxAndroid/issues/238
27-
// https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
28-
private static class MainThreadSchedulerHolder {
29-
static final Scheduler MAIN_THREAD_SCHEDULER = new LooperScheduler(Looper.getMainLooper());
30+
Scheduler main = hook.getMainThreadScheduler();
31+
if (main != null) {
32+
mainThreadScheduler = main;
33+
} else {
34+
mainThreadScheduler = new LooperScheduler(Looper.getMainLooper());
35+
}
3036
}
3137

3238
/** A {@link Scheduler} which executes actions on the Android UI thread. */
3339
public static Scheduler mainThread() {
34-
Scheduler scheduler =
35-
RxAndroidPlugins.getInstance().getSchedulersHook().getMainThreadScheduler();
36-
return scheduler != null ? scheduler : MainThreadSchedulerHolder.MAIN_THREAD_SCHEDULER;
40+
return INSTANCE.mainThreadScheduler;
3741
}
3842

3943
/** A {@link Scheduler} which executes actions on {@code looper}. */

0 commit comments

Comments
 (0)