将睡眠线程导入Schedulers.io-RxJava

时间:2019-03-31 19:49:56

标签: android multithreading rx-java

我目前正在测试RxJava,但感到困惑。
我把方法放在Thread.sleep(5000)

进入Schedulers.io()

CompositeDisposable compositeDisposable = new CompositeDisposable();
        compositeDisposable.add(longOperation()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableCompletableObserver() {
            @Override
            public void onComplete() {
                customToast("long operation done");
            }

            @Override
            public void onError(Throwable e) {

            }
        }));

我读到,我们应该将长时间的操作移到schedulers.io中,因为我们无法冻结UI线程,但是在这种情况下,我已经冻结了UI。怎么了?
longOperation()内部具有Thread.sleep(5000)。

//编辑后可致电

private void doSomething() throws InterruptedException {
        CompositeDisposable compositeDisposable = new CompositeDisposable();
        compositeDisposable.add(Observable.fromCallable(()-> longOperation())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableCompletableObserver() {
            @Override
            public void onComplete() {
                customToast("long operation done");
            }

            @Override
            public void onError(Throwable e) {

            }
        }));
    }

  private Completable longOperation() throws InterruptedException {
        Thread.sleep(5000);
        return Completable.complete();
    }

1 个答案:

答案 0 :(得分:1)

您应该使用defer(),以便它实际上在调度程序上执行,而不是在尝试创建可完成对象时。

private void doSomething() throws InterruptedException {
    CompositeDisposable compositeDisposable = new CompositeDisposable();
    compositeDisposable.add(Completable.defer(new Callable<CompletableSource>() {
        @Override
        public CompletableSource call() throws Exception {
            return longOperation();
        }
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableCompletableObserver() {
                @Override
                public void onComplete() {
                    customToast("long operation done");
                }

                @Override
                public void onError(Throwable e) {

                }
            }));
}

private Completable longOperation() throws InterruptedException {
    Thread.sleep(5000);
    return Completable.complete();
}