I have a singleton that takes a few seconds to instantiate. It makes the UI freezes. So I'm planning to make the getInstance()
method asynchronous. Is writing the following code a common practice?
/*
* The singleton class
*/
public class Singleton {
private static volatile Singleton instance;
public static Observable<Singleton> getInstance(Context context) {
return Observable.fromCallable(() -> {
synchronized (Singleton.class) {
if (instance == null)
instance = new Singleton(context.getApplicationContext());
}
return instance;
});
}
private Singleton(Context context) {
// long running process
}
// ...
}
/*
* The UI class
*/
public class UI extends Activity {
private Singleton singleton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Singleton.getInstance(this)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> {
UI.this.singleton = result
})
}
public void onButtonClick(View v) {
if (singleton != null)
singleton.someMethod();
}
}
If it's not, why isn't it and what's the better solution?