简体   繁体   English

通过返回一个 Observable 来使 Singleton 的 getInstance() 方法异步是否是个好主意<Singleton> ?

[英]Is It a Good Idea to Make Singleton's getInstance() Method Asynchronous by Making It Returns an Observable<Singleton>?

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.所以我打算使getInstance()方法异步。 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?如果不是,为什么不是,更好的解决方案是什么?

What you want is to cache the value returned from the callable, so the next time you call subscribe you do not want to execute the Callable again.您想要的是缓存从 callable 返回的值,因此下次您调用 subscribe 时,您不想再次执行 Callable。 For that use cache operator.为此,请使用缓存运算符。

Single<Integer> cachedValue = Single.fromCallable(() -> {
    Thread.sleep(3000);
    return 5;
}).cache();


cachedValue.subscribe(e -> System.out.println(System.currentTimeMillis() + ": " + e));
cachedValue.subscribe(e -> System.out.println(System.currentTimeMillis() + ": " + e));

You'll notice that the time for the second call is too close to the first one.您会注意到第二个调用的时间与第一个调用的时间太接近了。 At least < 3000 MS.至少 < 3000 毫秒。

Check this Safe Singleton .检查这个安全单例 Enums are the way to make it safe singleton枚举是使其安全单例的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM