I'm using RxKotlin together with Retrofit 2
I'm trying figure out how to have dynamic list of observers on a single operation.
The first observer should trigger the operation, and all additional observers should wait until the operation complete/fails
Once the operation complete,I need to make data manipulation (Store in cache/Memory) and then notify all the observers.
Here's what I did:
class UserManager
{
val observers = ArrayList<Observer<ArrayList<User>>>()
var isFetchingUsers = false
fun getUsers(observer: Observer<ArrayList<User>>)
{
observers.add(observer)
if (isFetchingUsers)
{
return
}
api.getUserList.observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<UserListResponse>
{
override fun onNext(response: UserListResponse)
{
// Do some manipulations on the response and notify all
observers.forEach {
it.onNext(response.getUsers())
}
}
override fun onError(e: Throwable)
{
observers.forEach {
it.onError(Throwable())
}
}
override fun onComplete()
{
isFetchingUsers = false
observers.clear()
}
override fun onSubscribe(d: Disposable)
{
}
})
}
}
Here's Retrofit observable creation (this one is in Java..)
/**
* Get users
*/
public Observable<UserListResponse> getUserList()
{
return mService.getUserList().subscribeOn(Schedulers.io());
}
I'm sure there's a better way for doing this
Thanks!