Created
January 22, 2021 10:02
-
-
Save manuelvicnt/6f3d16f5eda3874e9e155645180bad8b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| ) { | |
| 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