Reputation: 423
I am passing data to render the list as a Flow<>
. If it is empty, instead of the list, I need to display the inscription "No data". How can I set a condition to check if the flow is empty?
@Composable
fun HistoryLayout(viewModel: HistoryViewModel = viewModel()) {
val historyFlow = viewModel.historyStateFlow.collectAsLifecycleState().value
if (is historyFlow empty???) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
stringResource(R.string.emptylist),
textAlign = TextAlign.Center,
maxLines = MAX_LINES,
overflow = TextOverflow.Ellipsis,
)
}
} else {
HistoryTableList(historyFlow = historyFlow)
}
}
Upvotes: 0
Views: 2321
Reputation: 173
A better way of handling this would be to call .firstOrNull()
on the Flow. If there are no events emitted by the flow this will return null so you can check for that. If your flow emits an empty list the full check could be:
val hasItems = viewModel.historyStateFlow.firstOrNull()?.isNotEmpty() ?: false
Upvotes: 0
Reputation: 423
This trick helped me solve the problem, however i hope to still find a better solution
From Flow
i get LazyPagingItems<...>
, which has *.itemCount
method.
@Composable
fun HistoryLayout(viewModel: HistoryViewModel = viewModel()) {
val historyFlow = viewModel.historyStateFlow.collectAsLifecycleState().value
val historyItems: LazyPagingItems<HistoryRecordEntity> = historyFlow.collectAsLazyPagingItems()
if (historyItems.itemCount == 0) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
stringResource(R.string.emptylist),
textAlign = TextAlign.Center,
maxLines = MAX_LINES,
overflow = TextOverflow.Ellipsis,
)
}
} else {
HistoryTableList()
}
}
Upvotes: 0