Search code examples
kotlinrx-java2

Kotlin RxJava Call API in loop one by one, terminate the loop if any API response has desire result


I want to call API for each item in list and when the response received has desire result will return and terminate the loop.

My current code:

Observable.from(riffInPlayerSubscription)
.flatMap { item ->
   API.getAccessCheck(accessToken, item.itemId)
 }.flatMap { itemAccessResponse ->

                                    if (!itemAccessResponse.isExpired()) {
                                        credentialStore.hasActiveSubscription = true
                                        return@flatMap Observable.just(true)
                                    }
                         
}

But it loops for all items and doesn't terminate.


Solution

  • Use skipWhile and take:

    Observable.from(riffInPlayerSubscription)
    .flatMap { item ->
       API.getAccessCheck(accessToken, item.itemId)
    }
    .skipWhile { it.isExpired() }
    .take(1)
    .map { 
       credentialStore.hasActiveSubscription = true
       true
    }