Shudy
Shudy

Reputation: 7936

How to iterate over a list, and when finish launch a method with RXJava

I have a list of data models, so I have to apply a method that returns a view.

When everything is calculated, I have to launch a method, which makes another type of calculation.

The problem is that as I have it, at each iteration of the second method is launched.(for sure I'm missing something or doing bad, but my knowledge of RX is quite low)

Is it possible to make all the calculations for each method, and when finished, launch this method only once?

val markersViewList = hashMapOf<String, View>()
val subscription = Observable.fromIterable(retrivedUserInfoList)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
    .map { userInfo ->
        val markerLayout = setupUpForMarkerLayout(userInfo)
        if (markerLayout != null) {
            if (userInfo.userId == owner.uid) { //is owner
                markerViewList[OWNER] = markerLayout
            } else {
                if (!markerViewList.containsKey(userInfo.data1)) {
                    markerViewList[userInfo.data1] = markerLayout
                }
            }
        }
    }
    .subscribe {
        //THIS IS THE METHOD THAT ONLY HAS TO BE CALCULATED ONCE
        createImages(retrivedUserInfoList,markerViewList)
    }

addSubscription(subscription)

Upvotes: 0

Views: 167

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8442

You can use ignoreElements() operator for it:

val markersViewList = hashMapOf<String, View>()
val subscription = Observable.fromIterable(retrivedUserInfoList)
    .subscribeOn(Schedulers.computation())
    .observeOn(AndroidSchedulers.mainThread())
    .map { userInfo ->
        val markerLayout = setupUpForMarkerLayout(userInfo)
        if (markerLayout != null) {
            if (userInfo.userId == owner.uid) { //is owner
                markerViewList[OWNER] = markerLayout
            } else {
                if (!markerViewList.containsKey(userInfo.data1)) {
                    markerViewList[userInfo.data1] = markerLayout
                }
            }
        }
    }
    .ignoreElements()
    .subscribe {
        //THIS IS THE METHOD THAT ONLY HAS TO BE CALCULATED ONCE
        createImages(retrivedUserInfoList, markerViewList)
    }

addSubscription(subscription)

It will turn your Observable to Completable so your subscribe block will be invoked only once on complete.

Upvotes: 1

Related Questions