|
1 | 1 | package dev.dimension.flare.common
|
2 | 2 |
|
| 3 | +import androidx.compose.runtime.Composable |
3 | 4 | import androidx.compose.runtime.Immutable
|
| 5 | +import androidx.compose.runtime.State |
| 6 | +import androidx.compose.runtime.produceState |
4 | 7 | import androidx.paging.LoadState
|
5 | 8 | import androidx.paging.compose.LazyPagingItems
|
6 | 9 | import androidx.paging.compose.itemContentType
|
7 | 10 | import androidx.paging.compose.itemKey
|
8 | 11 | import dev.dimension.flare.ui.model.UiState
|
9 | 12 | import kotlinx.collections.immutable.ImmutableList
|
| 13 | +import kotlinx.collections.immutable.toImmutableList |
| 14 | +import kotlinx.coroutines.flow.Flow |
10 | 15 | import kotlin.contracts.ExperimentalContracts
|
11 | 16 | import kotlin.contracts.contract
|
12 | 17 |
|
@@ -47,6 +52,28 @@ public sealed class PagingState<T> {
|
47 | 52 |
|
48 | 53 | public abstract fun itemContentType(contentType: ((item: T) -> Any?)? = null): (index: Int) -> Any?
|
49 | 54 |
|
| 55 | + @Immutable |
| 56 | + internal data class ImmutableSuccess<T : Any>( |
| 57 | + private val data: ImmutableList<T>, |
| 58 | + override val itemCount: Int = data.size, |
| 59 | + override val isRefreshing: Boolean = false, |
| 60 | + override val appendState: LoadState = LoadState.NotLoading(endOfPaginationReached = true), |
| 61 | + ) : Success<T>() { |
| 62 | + override fun get(index: Int): T? = data.getOrNull(index) |
| 63 | + |
| 64 | + override fun peek(index: Int): T? = data.getOrNull(index) |
| 65 | + |
| 66 | + override suspend fun refreshSuspend() { |
| 67 | + } |
| 68 | + |
| 69 | + override fun retry() { |
| 70 | + } |
| 71 | + |
| 72 | + override fun itemContentType(contentType: ((item: T) -> Any?)?): (index: Int) -> Any? = { null } |
| 73 | + |
| 74 | + override fun itemKey(key: ((item: T) -> Any)?): (index: Int) -> Any = { it } |
| 75 | + } |
| 76 | + |
50 | 77 | @Immutable
|
51 | 78 | internal data class SingleSuccess<T : Any>(
|
52 | 79 | private val data: CacheableState<ImmutableList<T>>,
|
@@ -221,3 +248,11 @@ internal fun <T : Any> UiState<PagingState<T>>.flatten(): PagingState<T> =
|
221 | 248 | is UiState.Error -> PagingState.Error(throwable)
|
222 | 249 | is UiState.Success -> data
|
223 | 250 | }
|
| 251 | + |
| 252 | +@Composable |
| 253 | +internal fun <T : Any> Flow<List<T>>.collectPagingState(): State<PagingState<T>> = |
| 254 | + produceState<PagingState<T>>(initialValue = PagingState.Loading<T>()) { |
| 255 | + collect { |
| 256 | + value = PagingState.Success.ImmutableSuccess(it.toImmutableList()) |
| 257 | + } |
| 258 | + } |
0 commit comments