Search code examples
android-jetpack-composeandroid-navigationandroid-paging-3

paging3 data refresh when user click back button on android compose


I am developing an android app using:

  • Compose
  • Navigation
  • Paging3

The problem is

  1. User access "List Fragment" which shows some lists as "ViewPager - HorizontalPager(Compose)"
  2. Click one of them, and the user navigates to "Details Fragment".
  3. Click "back" button, and the user navigates to back "List Fragment".
  4. But at this time, the list is refreshed.

View (List Fragment):

@AndroidEntryPoint
class ArticlesFragment : Fragment() {

    private val vm: ArticlesViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        setup()
        return ComposeView(requireContext()).apply {
            setContent {
                Theme {
                    Scaffold {
                        Articles(vm.articles.collectAsLazyPagingItems())
                    }
                }
            }
        }
    }

    @OptIn(ExperimentalPagerApi::class)
    @Composable
    private fun Articles(articles: LazyPagingItems<Article>) {
        HorizontalPager(
            count = articles.itemCount,
            state = vm.pagerState,
        ) { page ->
            articles[page]?.let { article ->
                ArticleUi(article)
            }
        }
    }
}

ViewModel class:

@OptIn(ExperimentalPagerApi::class)
@HiltViewModel
class ArticlesViewModel @Inject constructor(
    private val getArticlesUsecase: GetArticlesUsecase
) {

    val pagerState = PagerState()

    val articles: Flow<PagingData<Article>> = getArticlesUsecase.get()

}

Solution

  • As @vitidev wrote in his comment.

    Use cachedIn to avoid refresh

    val articles: Flow<PagingData<Article>> = getArticlesUsecase.get().cachedIn(viewModelScope)