Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created January 22, 2021 10:02
Show Gist options
  • Select an option

  • Save manuelvicnt/6f3d16f5eda3874e9e155645180bad8b to your computer and use it in GitHub Desktop.

Select an option

Save manuelvicnt/6f3d16f5eda3874e9e155645180bad8b to your computer and use it in GitHub Desktop.
class TransactionsRepository(
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
private val transactionsCache = mutableMapOf<User, List<Transaction>()
private suspend fun addTransaction(user: User, transaction: Transaction) =
// CAREFUL! Access to the cache is not protected.
// Concurrency bugs can happen: threads can see stale data
// and race conditions may occur.
withContext(defaultDispatcher) {
if (transactionsCache.contains(user)) {
val oldList = transactionsCache[user]
val newList = oldList!!.toMutableList()
newList.add(transaction)
transactionsCache.put(user, newList)
} else {
transactionsCache.put(user, listOf(transaction))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment