UI -Status nicht ordnungsgemäß aktualisiert, nachdem Daten in Jetpack komponiert wurden
Posted: 12 Mar 2025, 13:27
Ich arbeite an einer Jetpack -Kompose -App, in der ich Buchdaten von einem Server mithilfe eines BooksViewModel von einem Server abholte. Die Benutzeroberfläche sollte basierend auf dem Status aktualisieren (, Erfolg oder fehler ). Die Benutzeroberfläche zeigt jedoch nur den Ladezustand an und wechselt nicht zu Erfolg oder fehler . Selbst wenn ich das Internet deaktiviere, zeigt die Benutzeroberfläche keine Fehlermeldung oder eine Snackbar an.
Dies ist mein booksViewModel :
oder Fehler und nur den Ladezustand anzeigen? Was könnte mit meinem Staatsmanagement falsch sein und wie kann ich es beheben?
Code: Select all
Loading
Code: Select all
@Composable
internal fun BookScreen(
onBackPressed: () -> Unit,
viewModel: BooksViewModel = koinViewModel()
) {
val uiState by viewModel.booksState.collectAsStateWithLifecycle()
val snackBarHostState = remember { SnackbarHostState() }
BackHandler(onBack = onBackPressed)
Scaffold(
snackbarHost = { SnackbarHost(snackBarHostState) }
) { contentPadding ->
when (uiState) {
is BooksUiState.Error -> {
LaunchedEffect(key1 = uiState) {
snackBarHostState.showSnackbar("Unknown Error")
}
}
is BooksUiState.Loading -> {
LoadingOverlay(isLoading = (uiState as BooksUiState.Loading).isLoading) {}
}
is BooksUiState.Success -> {
BookContent(
books = (uiState as BooksUiState.Success).books,
contentPadding = contentPadding
)
}
}
}
}
Code: Select all
class BooksViewModel(private val getBooksUseCase: GetBooksUseCase) : ViewModel() {
val booksState: StateFlow = getBooksFlow()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = BooksUiState.Loading(true)
)
private fun getBooksFlow(): Flow = flow {
val result = getBooksUseCase()
result.onSuccess { books ->
// instead of real books object I tested for mockBookList
emit(BooksUiState.Success(books = mockBooksList))
}.onFailure { error ->
emit(BooksUiState.Error(error = error))
}
}.catch { error ->
// Handle any unexpected exception during the flow execution
emit(BooksUiState.Error(error = error))
}.onCompletion {
// Ensure loading is set to false, even if cancelled or an error happens.
emit(BooksUiState.Loading(isLoading = false))
}
val mockBooksList = listOf(
BookApiModel(
id = 1,
title = "Book 1",
price = 100,
currencyCode = "USD",
author = "Vivek"
),
BookApiModel(
id = 2,
title = "Book 2",
price = 100,
currencyCode = "USD",
author = "Vivek"
),
BookApiModel(
id = 3,
title = "Book 3",
price = 100,
currencyCode = "USD",
author = "Vivek"
),
BookApiModel(
id = 4,
title = "Book 4",
price = 100,
currencyCode = "USD",
author = "Vivek"
),
BookApiModel(
id = 5,
title = "Book 5",
price = 100,
currencyCode = "USD",
author = "Vivek"
)
)
}
< /code>
Ich habe verifiziert, dass: < /p>
Die API funktioniert gut. Erfolg