evan
evan

Reputation: 1118

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

Upvotes: 0

Views: 603

Answers (1)

Sarath Kn
Sarath Kn

Reputation: 2725

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()

Upvotes: 1

Related Questions