I have a function that gets called from the response of a Flowable. It's an API request that returns a Single.
private fun syncUser() {
getUserUseCase.getUser() //Flowable DB (Room) call
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError { throwable -> throwable.printStackTrace() }
.subscribe({
users.postValue(it)
loadUserOptions()
isSyncing.postValue(false)
}, {
isSyncing.postValue(false)
it.printStackTrace()
log.e("Failed loading users")
})
.hold(this@MainViewModel) //extension function for CompositeDisposable.add() for interface CompositeDisposablesHolder
}
fun Disposable.hold(holder: CompositeDisposablesHolder) = holder.hold(this)
The getUserUseCase object is injected in the constructor.
The problem is that any time this is called, I see an increasing number of calls to the API. The first time its called, there's 1 API request, the 2nd time there's 2, the 3rd time there's 3 etc...
I think what's happening is that any time I call syncUser(), it adds this observer to the observer list, so there are duplicates in the list. The result is, if there's 10 duplicates, the subscribe block gets triggered 10 times, which causes the loadUserOptions() function to be called 10 times.
Am I correct to think that each call to syncUser() is creating a new duplicate Flowable? And if so, is there a way to fix my code? Or is it something else entirely?
Thanks