How with use RxJava update UI every one second in Android?
I'm trying to do something like this:
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;
}
But Thread.sleep() doing in ui thread. What I to do wrong?
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
rx.Observable.just(getSleep())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v->updateTime());//update textView
it's like
int stuff = getSleep();
rx.Observable.just(stuff)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v->updateTime());//update textView
If your code is running in the UI Thread then getSleep() will be executed in the UI Thread. You'll have to defer your call (using fromCallable for example).
rx.Observable.fromCallable(() -> getSleep())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v->updateTime());//update textView
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With