Rafiul Islam
11/28/2024, 1:40 PMisLoading
value before and after a network call and has no issues.
Option 1:
viewModelScope.launch {
_uiState.update { it.copy(isLoading = true) }
val result = getSomethingUseCase()
if (result.isSuccess) {
_uiState.update {
it.copy(isLoading = false, data = result.getOrDefault(emptyList()))
}
} else {
_uiState.update {
it.copy(isLoading = false, errorMessage = Error.unknownError())
}
}
}
Problem: have to isLoading = false everything let's say I handle multiple types of error then with when block.
See more in the thread 🧵Rafiul Islam
11/28/2024, 1:42 PMviewModelScope.launch {
_uiState.update { it.copy(isLoading = true) }
val result = getSomethingUseCase()
_uiState.update { it.copy(isLoading = false) }
if (result.isSuccess) {
_uiState.update {
it.copy(data = result.getOrDefault(emptyList()))
}
} else {
_uiState.update {
it.copy(errorMessage = Error.unknownError())
}
}
}
isLoading = false just after the network call even before updating the stateRafiul Islam
11/28/2024, 1:44 PMviewModelScope.launch {
try {
_uiState.update { it.copy(isLoading = true) }
val result = getSomethingUseCase()
if (result.isSuccess) {
_uiState.update {
it.copy(data = result.getOrDefault(emptyList()))
}
} else {
_uiState.update { it.copy(errorMessage = Error.unknownError()) }
}
} finally {
_uiState.update { it.copy(isLoading = false) }
}
Using try and finally
Problem: Introducing an unnecessary try and finally blockflorent
11/30/2024, 1:37 PMRafiul Islam
11/30/2024, 4:46 PMHimanshu Pal
12/04/2024, 4:56 AMsealed class OResponseWrapper<out T> {
data class Success<out T>(val data: T) : OResponseWrapper<T>()
data class Error(val message: String? = null, val cause: Throwable? = null) :
OResponseWrapper<Nothing>()
data object Loading : OResponseWrapper<Nothing>()
}
And, in this case I'll do separate handlings for Success and Error state and instead of handling Loading state, I'll show loader in else
block of when statement.
By doing this, suppose i added one more class later on as:
sealed class OResponseWrapper<out T> {
data class Success<out T>(val data: T) : OResponseWrapper<T>()
data class Error(val message: String? = null, val cause: Throwable? = null) :
OResponseWrapper<Nothing>()
data object Loading : OResponseWrapper<Nothing>()
data object LoadingMore : OResponseWrapper<Nothing>()
}
This LoadingMore
is used for showing progress when I am doing pagination in a recycler view. So, I'll handle this LoadingMore explicitly on the intended places only.