Jitender Sharma
Jitender Sharma

Reputation: 53

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.

Upvotes: 0

Views: 444

Answers (1)

akarnokd
akarnokd

Reputation: 70017

Use skipWhile and take:

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

Upvotes: 2

Related Questions