mercredi 25 décembre 2019

Is It a Good Idea to Make Singleton's getInstance() Method Asynchronous by Making It Returns an Observable

I have a singleton that takes some time to instantiate. So I'm planning to make the getInstance() method asynchronous. Is writing the following code a common practice?

public class Singleton {

    private static volatile Singleton instance;

    public static Observable<Singleton> getInstance(Params params) {
        return Observable.fromCallable(() -> {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton(params);
                }
            }
            return instance;
        });
    }

    // ...
}

If not, why isn't it and what's the better solution?

Aucun commentaire:

Enregistrer un commentaire