通过使Singleton的getInstance()方法返回可观察的< Singleton>来使其异步,是一个好主意吗? [英] Is It a Good Idea to Make Singleton's getInstance() Method Asynchronous by Making It Returns an Observable<Singleton>?

查看:60
本文介绍了通过使Singleton的getInstance()方法返回可观察的< Singleton>来使其异步,是一个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单例,需要实例化几秒钟.它使UI冻结.因此,我计划使 getInstance()方法异步.编写以下代码是一种惯例吗?

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?

推荐答案

您想要的是缓存可调用对象返回的值,因此,下次调用订阅时,您不想再次执行可调用对象.为了那个原因使用缓存运算符.

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. 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));

您会注意到第二个呼叫的时间与第一个呼叫的时间太近.至少<3000 MS.

You'll notice that the time for the second call is too close to the first one. At least < 3000 MS.

这篇关于通过使Singleton的getInstance()方法返回可观察的&lt; Singleton&gt;来使其异步,是一个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆