I have a Single
that makes a REST
call. This Single can get called up to 10 times at the same time, which ends up in 10 requests of the same thing. I don't see any way to get a hot Single
and I tried using cache()
when returning the Single
to no avail.
How can I achieve this?
Here is the logic I follow to make the call:
fun getUser(userID: UUID): Single<User> {
if (userCache.containsUser(userID)) {
// Just return the value already saved in the cache
return Single.create {
it.onSuccess(getUserFromCache(userID))
}
} else {
// Make rest call, add user in cache, and then return that user
return Single.fromCallable {
val user = getUserFromRest(userID).blockingGet()
userCache.addUser(user)
return@fromCallable user
}.cache()
}
}
I have updated the previous code to implement caching:
private var ongoingRequests: HashMap<UUID, Single<User>> = HashMap()
fun getUser(userID: UUID): Single<User> {
if (userCache.containsUser(userID)) {
return Single.create {
it.onSuccess(getUserFromCache(userID))
}
} else if (ongoingRequests.containsKey(userID)) {
return ongoingRequests[userID]!!
} else {
val request = Single.create<User> {
getUserFromRest(userID).subscribe(
{ user ->
userCache.addUser(user)
ongoingRequests.remove(userID)
it.onSuccess(user)
},
{
}
)
}.cache()
ongoingRequests[userID] = request
return request
}
}