Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Created January 22, 2021 10:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manuelvicnt/dc664eb50a4487994338f06e76fe9bff to your computer and use it in GitHub Desktop.
Save manuelvicnt/dc664eb50a4487994338f06e76fe9bff to your computer and use it in GitHub Desktop.
class TransactionsRepository(
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
// Mutex protecting the cache mutable state
private val cacheMutex = Mutex()
private val transactionsCache = mutableMapOf<User, List<Transaction>()
private suspend fun addTransaction(user: User, transaction: Transaction) =
withContext(defaultDispatcher) {
// Mutex makes the read&write cache operation thread safe
cacheMutex.withLock {
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