Created
January 22, 2021 10:05
-
-
Save manuelvicnt/dc664eb50a4487994338f06e76fe9bff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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