Reputation: 2362
I am new to Rx and I am making one API call using Rx. It is working but the problem is that it is continuously making the API after I received response or error. I am using the MVVM pattern.
Here is my code how I am observing result in View Model:
val usersList = getGitHubUsersUseCase.getUsers(since.toInt())
usersList?.subscribeOn(Schedulers.io())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe({
if (it.error == null) {
var sinceState = SinceState(since, since.isNotEmpty(), it.users)
stateLiveData.postValue(sinceState)
} else {
var sinceState =
SinceState(since, since.isNotEmpty(), emptyList(), it.error?.message)
stateLiveData.postValue(sinceState)
}
}, {
var sinceState = SinceState(since, since.isNotEmpty(), emptyList(), it.message)
stateLiveData.postValue(sinceState)
})
How do I stop observing once I received a response or an error? Am I missing something?
If I don't stop this continuously making calls, then it makes too many API calls and server start returning:
HTTP 403 forbidden
Upvotes: 0
Views: 304
Reputation: 193
To get a response only once, use the 'Single' type. You can convert your data stream to a Single using
val usersList = getGitHubUsersUseCase.getUsers(since.toInt()).firstOrError()
Upvotes: 1