no news
no news

Reputation: 1070

RxJava Thread.sleep in another thread

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?

Upvotes: 3

Views: 5089

Answers (2)

Maksim Ostrovidov
Maksim Ostrovidov

Reputation: 11058

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

Upvotes: 3

dwursteisen
dwursteisen

Reputation: 11515

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

Upvotes: 1

Related Questions