Skip to content

Commit

Permalink
[fix] Collect paging data with lifecycle https://slack-chats.kotlinla…
Browse files Browse the repository at this point in the history
  • Loading branch information
SkyD666 committed Jan 22, 2025
1 parent 925fb7a commit 0d0cc70
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
22 changes: 22 additions & 0 deletions app/src/main/java/com/skyd/rays/ext/LazyPagingExt.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.skyd.rays.ext

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.flowWithLifecycle
import androidx.paging.PagingData
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import kotlinx.coroutines.flow.Flow
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

@Composable
fun <T : Any> Flow<PagingData<T>>.collectAsLazyPagingItemsWithLifecycle(
context: CoroutineContext = EmptyCoroutineContext
): LazyPagingItems<T> {
val lifecycle = LocalLifecycleOwner.current.lifecycle
return remember(this, lifecycle) {
flowWithLifecycle(lifecycle)
}.collectAsLazyPagingItems(context)
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ class SearchRepository @Inject constructor(

fun requestStickerWithTagsListWithAllSearchDomain(keyword: String): Flow<PagingData<StickerWithTags>> {
return flow { emit(genSql(k = keyword, useSearchDomain = { _, _ -> true })) }
.flowOn(Dispatchers.IO)
.flatMapLatest { Pager(pagingConfig) { stickerDao.getStickerWithTagsPaging(it) }.flow }
.flowOn(Dispatchers.IO)
}

data class SearchResult(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import androidx.paging.compose.collectAsLazyPagingItems
import com.skyd.rays.R
import com.skyd.rays.base.mvi.MviEventListener
import com.skyd.rays.base.mvi.getDispatcher
import com.skyd.rays.ext.collectAsLazyPagingItemsWithLifecycle
import com.skyd.rays.ext.navigate
import com.skyd.rays.ext.plus
import com.skyd.rays.model.bean.StickerWithTags
Expand Down Expand Up @@ -94,7 +95,8 @@ fun StickersListScreen(query: String, viewModel: StickersListViewModel = hiltVie
when (val listState = uiState.listState) {
ListState.Init -> Unit
is ListState.Success -> {
val lazyPagingItems = listState.stickerWithTagsPagingFlow.collectAsLazyPagingItems()
val lazyPagingItems =
listState.stickerWithTagsPagingFlow.collectAsLazyPagingItemsWithLifecycle()
StickerList(
count = lazyPagingItems.itemCount,
data = { lazyPagingItems[it]!! },
Expand Down

0 comments on commit 0d0cc70

Please sign in to comment.