Moved error state holding to the TabViewModel

This commit is contained in:
Abdelilah El Aissaoui 2022-04-08 22:05:22 +02:00
parent 1f58114404
commit 8650b1a43c
3 changed files with 12 additions and 8 deletions

View File

@ -2,7 +2,9 @@ package app
import app.di.TabScope import app.di.TabScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import javax.inject.Inject import javax.inject.Inject
@ -13,16 +15,16 @@ class ErrorsManager @Inject constructor() {
val errorsList: StateFlow<List<Error>> val errorsList: StateFlow<List<Error>>
get() = _errorsList get() = _errorsList
private val _lastError = MutableStateFlow<Error?>(null) private val _error = MutableSharedFlow<Error?>()
val lastError: StateFlow<Error?> = _lastError val error: SharedFlow<Error?> = _error
suspend fun addError(error: Error) = withContext(Dispatchers.IO) { suspend fun addError(error: Error) = withContext(Dispatchers.IO) {
_errorsList.value = _errorsList.value.toMutableList().apply { _errorsList.value = _errorsList.value.toMutableList().apply {
add(error) add(error)
} }
_lastError.value = error _error.emit(error)
println("LastError flow: ${_lastError.value}") println("LastError flow: $error")
} }
fun removeError(error: Error) { fun removeError(error: Error) {

View File

@ -34,14 +34,14 @@ fun AppTab(
tabViewModel: TabViewModel, tabViewModel: TabViewModel,
) { ) {
val errorManager = tabViewModel.errorsManager val errorManager = tabViewModel.errorsManager
val lastError by errorManager.lastError.collectAsState() val lastError by errorManager.error.collectAsState(null)
var showError by remember { mutableStateOf(false) } val showError by tabViewModel.showError.collectAsState()
if (lastError != null) { if (lastError != null) {
LaunchedEffect(lastError) { LaunchedEffect(lastError) {
showError = true tabViewModel.showError.value = true
delay(5000) delay(5000)
showError = false tabViewModel.showError.value = false
} }
} }

View File

@ -70,6 +70,8 @@ class TabViewModel @Inject constructor(
private val _repositoryState = MutableStateFlow(RepositoryState.SAFE) private val _repositoryState = MutableStateFlow(RepositoryState.SAFE)
val repositoryState: StateFlow<RepositoryState> = _repositoryState val repositoryState: StateFlow<RepositoryState> = _repositoryState
val showError = MutableStateFlow(false)
init { init {
tabState.managerScope.launch { tabState.managerScope.launch {
tabState.refreshData.collect { refreshType -> tabState.refreshData.collect { refreshType ->