Search code examples
javaandroidrx-java

Rxjava how to create a thread and return text to UI


I want run a new thread, when user click on the button. In this thread i call Sleep(2000) after "i++" and return string ("Text" + i) in TextView. I have example but it don't work:

Observable.create(new Observable.OnSubscribe<Void>() {
    @Override
    public void call(Subscriber<? super Void> subscriber) {
        SystemClock.sleep(2000); 
        i++;

        subscriber.onNext(null);

        subscriber.onCompleted(); 
    }
})
        .subscribeOn(Schedulers.computation()) 
        .observeOn(AndroidSchedulers.mainThread()) 
        .subscribe(new Action1<Void>() { 
            @Override
            public void call(Void aVoid) {
                // code like text.setText("text" + i)
            }
        });

Solution

  • Do you use RxJava1 or RxJava2/3?

    Do you want to create a new Thread on very subscription? If yes, when you would use Schedulers.newThread() instead of .subscribeOn(Schedulers.computation())

    In RxJava2/3 it is not allowed to emit null subscriber.onNext(null);. This is actually your issue. You want to emit i++ and not null.

    I would rather do something like this:

        AtomicInteger i = new AtomicInteger(0);
          
          Single.fromCallable(() -> {
            Thread.sleep(1000);
            
            return i.incrementAndGet();
          }).subscribeOn(Schedulers.computation())
            .observeOn(....)
            .subscribe(v -> ...)
    

    It is not recommended to mutate state from different threads without any synchronization, therefore use AtomicInteger.