Hello.

I just started trying to deal with RxJava and for several hours now I've been RxJava to execute the method in a separate thread for each list item. The bottom line is this: there is an ArrayList some Photo objects. For each of them, you need to perform a method that works with the network and increase the value inside the progress bar of the dialog box after each execution. Now it looks like this for me:

 Observable.defer(() -> Observable.just(photoArrayList)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .flatMapIterable(list -> list) .filter(photo -> photo != null) .map(photo -> некийМетод(photo)) .subscribe(result -> loadingDialog.incrementProgress(1), e -> onImagesUploadComplete(false), () -> onImagesUploadComplete(true)); 

Obviously, this is done clumsily and throws a NetworkOnMainThreadException .

Honestly, I don’t understand where else, except in the just() method you can run a method not in the UI stream? Thank you in advance for your response.

    1 answer 1

    The fact is that after observeOn(AndroidSchedulers.maintThread()) , everything will be executed in the UI stream. The principle is simple:

     someObservable //все вызовы здесь будут выполняться в THREAD_1 .subscribeOn(THREAD_1) .observeOn(THREAD_2) //здесь все вызовы в THREAD_2 .observeOn(THREAD_3) //здесь все вызовы в THREAD_3 //и так далее 

    By "all calls" I mean any map() , doOnNext/Error/Complete() , subscribe() - in short, everything.

    To make everything work for you, it is enough to transfer subscribeOn() and observeOn() in this way:

     Observable.defer(() -> Observable.just(photoArrayList)) .flatMapIterable(list -> list) .filter(photo -> photo != null) .map(photo -> некийМетод(photo)) //так как этот вызов до subscribeOn(io), то map будет выполняться в io-потоке .subscribeOn(Schedulers.io()) //чтобы все верхние функторы работали в `io` потоке .observeOn(AndroidSchedulers.mainThread()) //все нижние функторы будут выполняться в UI-потоке .subscribe(result -> loadingDialog.incrementProgress(1), e -> onImagesUploadComplete(false), () -> onImagesUploadComplete(true)); 
    • Indeed, all turned out well. Thank you very much for your help, otherwise I would have been trying to solve the problem. It is strange that among all the "guides for beginners" in both the Russian and the English-speaking segment I have not met mention of this "feature." - ahgpoug
    • one
      it seems like it is revealed here youtube.com/watch?v=3jdvLrYZfB4 - andreich