Android KotlinRx API call making continuously in background

284 Views Asked by At

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

1

There are 1 best solutions below

2
On

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