collectAsLazyPagingItems

Functions summary

LazyPagingItems<T>

Collects values from this Flow of PagingData and represents them inside a LazyPagingItems instance.

Cmn

Functions

Flow.collectAsLazyPagingItems

@Composable
fun <T : Any> Flow<PagingData<T>>.collectAsLazyPagingItems(
    context: CoroutineContext = EmptyCoroutineContext
): LazyPagingItems<T>

Collects values from this Flow of PagingData and represents them inside a LazyPagingItems instance. The LazyPagingItems instance can be used for lazy foundations such as LazyListScope.items in order to display the data obtained from a Flow of PagingData.

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import androidx.paging.LoadState
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.compose.collectAsLazyPagingItems

val myBackend = remember { TestBackend(DATA) }

val pager = remember {
    Pager(
        PagingConfig(
            pageSize = myBackend.DataBatchSize,
            enablePlaceholders = true,
            maxSize = 200,
        )
    ) {
        myBackend.getAllData()
    }
}

val lazyPagingItems = pager.flow.collectAsLazyPagingItems()

LazyColumn {
    if (lazyPagingItems.loadState.refresh == LoadState.Loading) {
        item {
            Text(
                text = "Waiting for items to load from the backend",
                modifier =
                    Modifier.fillMaxWidth().wrapContentWidth(Alignment.CenterHorizontally),
            )
        }
    }

    items(count = lazyPagingItems.itemCount) { index ->
        val item = lazyPagingItems[index]
        Text("Index=$index: $item", fontSize = 20.sp)
    }

    if (lazyPagingItems.loadState.append == LoadState.Loading) {
        item {
            CircularProgressIndicator(
                modifier =
                    Modifier.fillMaxWidth().wrapContentWidth(Alignment.CenterHorizontally)
            )
        }
    }
}
Parameters
context: CoroutineContext = EmptyCoroutineContext

the CoroutineContext to perform the collection of PagingData and CombinedLoadStates.