Hey all, so I want to prevent making duplicate req...
# coroutines
b
Hey all, so I want to prevent making duplicate requests to a server. Does it make sense to store a bunch of
Deferred<T>
s and reuse them? Or is this a coroutine anti-pattern? I'm pretty new to coroutines so I'm just wonder if there is a better way.
Copy code
private val notesDeferred = HashMap<String, Deferred<Resource<String>>>()
suspend fun getNotes(id: String): Resource<String>{
    if(notesDeferred.containsKey(id) && notesDeferred.get(id)!!.isActive){
        return notesDeferred.get(id)!!.await()
    } else {
        val newRequest = GlobalScope.async {
            remoteSource.getNotes(id)
        }
        notesDeferred.put(id, newRequest)
        return newRequest.await()
    }
}
w
But I don't know whether this is the best way. Could somebody please tell us if there is a better way?
b
Interesting solution. What do you use launch time for?
w
It's for something like that the second
async
starts after the first
async
finished. In this case, the second
async
do the task as usual (not
await
the first task).
b
Ok, makes sense. I guess I'm using
.isActive
to do that.
👍🏻 1