RxJava Thread.sleep在另一个线程中

时间:2016-11-10 13:45:40

标签: android rx-java

如何在Android中每隔一秒使用RxJava更新UI? 我正在尝试做这样的事情:

 for (int i = 0; i <10 ; i++) { //test
               rx.Observable.just(getSleep())
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(v->updateTime());//update textView
        }

    private <T> int getSleep() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 0;
    }

但Thread.sleep()在ui线程中执行。 我做错了什么?

2 个答案:

答案 0 :(得分:3)

Observable.interval(1, TimeUnit.SECONDS) //emits item every second
            .observeOn(AndroidSchedulers.mainThread()) //switches thread from computation (interval's default) to UI
            .subscribe(i -> updateUI()); //update your textView

答案 1 :(得分:1)

rx.Observable.just(getSleep())
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(v->updateTime());//update textView

就像

int stuff = getSleep();
rx.Observable.just(stuff)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(v->updateTime());//update textView

如果您的代码在UI线程中运行,那么将在UI线程中执行getSleep()。您必须推迟拨打电话(例如,使用fromCallable)。

     rx.Observable.fromCallable(() -> getSleep())
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(v->updateTime());//update textView