Warum wird in CollectAsStateWithlifecycle für StateFlow in CollectAsStateWithlifecycle benötigt?Android

Forum für diejenigen, die für Android programmieren
Anonymous
 Warum wird in CollectAsStateWithlifecycle für StateFlow in CollectAsStateWithlifecycle benötigt?

Post by Anonymous »

Ich habe ein ViewModel, das einen Stateflow enthüllt, der den UI -Zustand einer Buchliste darstellt: < /p>

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),
)
}
In meinem @compositable sammle ich diesen Status mit CollectAsStateWithlifecycle :

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()
}
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.>

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post