CLOVIS
07/27/2019, 7:25 PMgildor
07/28/2019, 1:02 AMasync
as the simplest way to create Deferred that encapsulate some value and provides suspend function to access it
If you need something more complicated than a Map with Deffered, you can use the same approach with sync primivies, just use their suspend counterpart: Mutex and Semaphore from kotlinx.coroutinesCLOVIS
07/28/2019, 9:18 AMgildor
07/28/2019, 12:13 PMgildor
07/28/2019, 12:15 PMgildor
07/28/2019, 12:22 PMval cache: MutableMap<String, Deferred<User>>
suspend fun loadUser(id: String): User {
// Get existing deferred or create new one
val deferred = cache.getOrPut(id) {
async {
storage.loadUser(id)
}
}
// I prefer use suspend function, but you can just return deferred if you want
return deferred.await()
}
gildor
07/28/2019, 12:23 PMCLOVIS
07/28/2019, 5:27 PMgildor
07/29/2019, 12:38 AMactor
and part of kotlinx.coroutines. for sure you can run it in GlobalScope (or just create own ApplicationScope with app lifecycle, if you want be explicit)