Add updateToPendingOrLoading helper method (#390)

This commit is contained in:
David Perez 2023-12-13 18:35:33 -06:00 committed by Álison Fernandes
parent 5932ebb5c6
commit 36e913b680
3 changed files with 35 additions and 10 deletions

View file

@ -2,7 +2,9 @@ package com.x8bit.bitwarden.data.platform.repository.util
import com.x8bit.bitwarden.data.platform.repository.model.DataState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.transformWhile
import kotlinx.coroutines.flow.update
/**
* Maps the data inside a [DataState] with the given [transform].
@ -24,3 +26,15 @@ fun <T : Any?> Flow<DataState<T>>.takeUntilLoaded(): Flow<DataState<T>> = transf
emit(it)
it !is DataState.Loaded
}
/**
* Updates the [DataState] to [DataState.Pending] if there is data present or [DataState.Loading]
* if no data is present.
*/
fun <T : Any?> MutableStateFlow<DataState<T>>.updateToPendingOrLoading() {
update { dataState ->
dataState.data
?.let { data -> DataState.Pending(data = data) }
?: DataState.Loading
}
}

View file

@ -13,6 +13,7 @@ import com.x8bit.bitwarden.data.platform.datasource.network.util.isNoConnectionE
import com.x8bit.bitwarden.data.platform.manager.dispatcher.DispatcherManager
import com.x8bit.bitwarden.data.platform.repository.model.DataState
import com.x8bit.bitwarden.data.platform.repository.util.map
import com.x8bit.bitwarden.data.platform.repository.util.updateToPendingOrLoading
import com.x8bit.bitwarden.data.platform.util.asSuccess
import com.x8bit.bitwarden.data.platform.util.flatMap
import com.x8bit.bitwarden.data.platform.util.zip
@ -91,16 +92,8 @@ class VaultRepositoryImpl constructor(
override fun sync() {
if (!syncJob.isCompleted || willSyncAfterUnlock) return
vaultDataMutableStateFlow.value.data?.let { data ->
vaultDataMutableStateFlow.update {
DataState.Pending(data = data)
}
}
sendDataMutableStateFlow.value.data?.let { data ->
sendDataMutableStateFlow.update {
DataState.Pending(data = data)
}
}
vaultDataMutableStateFlow.updateToPendingOrLoading()
sendDataMutableStateFlow.updateToPendingOrLoading()
syncJob = scope.launch {
syncService
.sync()

View file

@ -23,4 +23,22 @@ class DataStateExtensionsTest {
awaitComplete()
}
}
@Test
fun `updateToPendingOrLoading should change the DataState to Pending when data is present`() {
val mutableStateFlow = MutableStateFlow<DataState<Unit>>(DataState.Loaded(Unit))
mutableStateFlow.updateToPendingOrLoading()
assertEquals(DataState.Pending(Unit), mutableStateFlow.value)
}
@Test
fun `updateToPendingOrLoading should change the DataState to Loading when data is absent`() {
val mutableStateFlow = MutableStateFlow<DataState<Unit>>(DataState.Error(Throwable("Fail")))
mutableStateFlow.updateToPendingOrLoading()
assertEquals(DataState.Loading, mutableStateFlow.value)
}
}