Warum wird in CollectAsStateWithlifecycle für StateFlow in CollectAsStateWithlifecycle benötigt?
Posted: 18 Mar 2025, 18:25
Ich habe ein ViewModel, das einen Stateflow enthüllt, der den UI -Zustand einer Buchliste darstellt: < /p>
In meinem @compositable sammle ich diesen Status mit CollectAsStateWithlifecycle :
Da BookState bereits ein StateFlow mit einem Anfangswert ist (booksuistat.loading (true)) müssen wir initialValue übergeben, um eine Sammlung zu sammeln, um zu sammeln.>
Code: Select all
class BooksViewModel(private val getBooksUseCase: GetBooksUseCase) : ViewModel() {
val booksState: Flow = flow {
val result = getBooksUseCase()
result.onSuccess {
emit(BooksUiState.Success(it))
}.onFailure {
emit(BooksUiState.Error(it))
}
}.onStart {
emit(BooksUiState.Loading(true))
}.onCompletion {
emit(BooksUiState.Loading(false))
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = BooksUiState.Loading(true),
)
}
Code: Select all
@Composable
fun BookScreen(
onBackPressed: () -> Unit,
viewModel: BooksViewModel = koinViewModel()
) {
val uiState by viewModel.booksState.collectAsStateWithLifecycle(
initialValue = BooksUiState.Loading(true)
)
BackHandler(onBack = onBackPressed)
BookContent()
}