android - RxJava 在相同的阻塞 UI 线程上运行并且不显示 AlertDialog

标签 android multithreading rx-java

我正在尝试使用 RxJava 在加载某些方法期间显示 AlertDialog。它不起作用,UI 被阻塞 2 秒,当使用调试器单步执行它时,调试器显示它在 UI 线程上运行。我已经添加了 Schedulers.IO,那么我做错了什么?

boolean initialize() {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
    }
    return true;
}

public AlertDialog showSomePopup(Context context, String msg) {
    return new AlertDialog.Builder(context)
            .setTitle("Loading...")
            .setMessage(msg)
            .setPositiveButton("Ok", null)
            .show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final AlertDialog dialog = showSomePopup(this, "Waiting ..");

    Single.just(initialize())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Boolean>() {
        @Override
        public void accept(@NonNull Boolean aBoolean) throws Exception {
            dialog.dismiss();
        }
    });
}

最佳答案

问题是 .subscribe()initialize() 方法未发出之前不会被调用(即当您使用 .just(),直到 initialize() 不返回。

关于android - RxJava 在相同的阻塞 UI 线程上运行并且不显示 AlertDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46640963/

相关文章:

java - 错误: package android. util不存在

安卓工作室 : "shared" module directories of KMM project keep getting unmarked as sources root

c# - 正在返回什么任务,为什么这个任务状态是 RanToCompletion

android - 如果我的 RxJava 2 调用返回 Single 或 Maybe,我还需要使用 CompositeDisposable 吗?

android - Android SIP根本没有音频

android - 在抽屉导航中切换 fragment 时短黑闪烁

java - 我可以用 Java 获取 Linux "max user processes"吗?

multithreading - 跟踪后台进程?

java - 热衷于使用 RxAndroid 跟踪进度?

java - 有没有办法使用 RxJava 让方法在多个线程上运行