Fixed concurrency errors when trying to update recent repositories

This commit is contained in:
Abdelilah El Aissaoui 2022-06-11 13:42:18 +02:00
parent b399947734
commit 9bf5fc4663

View file

@ -1,6 +1,7 @@
package app package app
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.serialization.decodeFromString import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
@ -11,6 +12,8 @@ import javax.inject.Singleton
class AppStateManager @Inject constructor( class AppStateManager @Inject constructor(
private val appPreferences: AppPreferences, private val appPreferences: AppPreferences,
) { ) {
private val mutex = Mutex()
private val _openRepositoriesPaths = mutableMapOf<Int, String>() private val _openRepositoriesPaths = mutableMapOf<Int, String>()
val openRepositoriesPathsTabs: Map<Int, String> val openRepositoriesPathsTabs: Map<Int, String>
get() = _openRepositoriesPaths get() = _openRepositoriesPaths
@ -25,21 +28,26 @@ class AppStateManager @Inject constructor(
get() = _latestOpenedRepositoriesPaths.firstOrNull() ?: "" get() = _latestOpenedRepositoriesPaths.firstOrNull() ?: ""
fun repositoryTabChanged(key: Int, path: String) = appStateScope.launch(Dispatchers.IO) { fun repositoryTabChanged(key: Int, path: String) = appStateScope.launch(Dispatchers.IO) {
// Do not save already saved repos mutex.lock()
if (!_openRepositoriesPaths.containsValue(path)) try {
_openRepositoriesPaths[key] = path // Do not save already saved repos
if (!_openRepositoriesPaths.containsValue(path))
_openRepositoriesPaths[key] = path
// Remove any previously existing path // Remove any previously existing path
_latestOpenedRepositoriesPaths.removeIf { it == path } _latestOpenedRepositoriesPaths.removeIf { it == path }
// Add the latest one to the beginning // Add the latest one to the beginning
_latestOpenedRepositoriesPaths.add(0, path) _latestOpenedRepositoriesPaths.add(0, path)
if (_latestOpenedRepositoriesPaths.count() > 5) if (_latestOpenedRepositoriesPaths.count() > 5)
_latestOpenedRepositoriesPaths.removeLast() _latestOpenedRepositoriesPaths.removeLast()
updateSavedRepositoryTabs() updateSavedRepositoryTabs()
updateLatestRepositoryTabs() updateLatestRepositoryTabs()
} finally {
mutex.unlock()
}
} }
fun repositoryTabRemoved(key: Int) = appStateScope.launch(Dispatchers.IO) { fun repositoryTabRemoved(key: Int) = appStateScope.launch(Dispatchers.IO) {