Search code examples
rx-java2rx-android

rxjava background process and update ui intermediately


A lengthy background operation and it has FOR loop. after each iteration in the loop is completed I need to update UI. how can I achieve this in RX java without waiting for all the iteration to get completed or writing 2 observables?

doInBackGround() {

       //step 1
       List<Object> list= < time consuming logic >

       //step 2
       for(Object item: list) {
          < time consuming logic >
          updateUi();
       }

}

it can be done using AsyncTask/Threads. but I am experimenting with RX


Solution

  • I think you are getting a list from a long running operation, and you have to iterate over the list and perform a long running operation again on each item in the list. Meanwhile you have to update the UI when each item is done with the long running task. If you are trying to do this, you could try something like

     Observable.fromCallable {
              val list = timeConsumingLogic()
              list // return the list
            }.flatMap { source: List<Any>? -> Observable.fromIterable(source) } // iterate through each item
                .map { item: Any? ->
                     // perform time consuming logic on each item
                    item 
                }
                .observeOn(AndroidSchedulers.mainThread()) // do the next step in main thread
                .doOnNext { item: Any? -> 
                    // perform UI operation on each Item 
                     }
                .subscribeOn(Schedulers.io()) //  start the process in a background thread
                .subscribe()