https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

bsimmons

08/28/2020, 11:56 AM
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

wcaokaze

08/28/2020, 12:46 PM
But I don't know whether this is the best way. Could somebody please tell us if there is a better way?
b

bsimmons

08/28/2020, 1:04 PM
Interesting solution. What do you use launch time for?
w

wcaokaze

08/28/2020, 1:15 PM
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

bsimmons

08/28/2020, 1:26 PM
Ok, makes sense. I guess I'm using
.isActive
to do that.
👍🏻 1
17 Views