2

I am learning pagination using paging3 from the jetpack library. I am making a call to an api to receive a list of articles. I've noticed that the result received after making the call in the repository using the Pager is a flow of PagingData containing the desired result like so:

Flow<PagingData<Articles>>

When I receive this flow in my ViewModel I would like to convert it into a Stateflow. I have tried using the stateIn operator but it requires a default value which I think would be a StateFlow , this is where I am stuck. How can I convert the flow of PagingData into a Stateflow and is it advisable to do so?

  • Why do you need to convert this to a `StateFlow`? – Arpit Shukla Nov 17 '21 at 06:45
  • I think It´s interesting question. How can I handle an initial state or error state without StateFlow in this case? https://stackoverflow.com/questions/68483347/android-mvi-using-stateflow-and-paging-3 This user suggests to use flow inside a success state of stateFlow but I don´t think is the best solution. Any other? – di0n0s Mar 28 '22 at 11:16

2 Answers2

1

I also have a question: why do you want to convert the Flow of PagingData into a Stateflow when you get the Article and show them on UI?

In my practice, no need to touch Stateflow. If I want to get Articles with Paging lib 3. Pay attention to Flow, ArticleRemoteMediator: RemoteMediator<Int, ArticleEntity> ...

I think this article can help you to archive your goal. (getting article with Paging 3) https://medium.com/nerd-for-tech/pagination-in-android-with-paging-3-retrofit-and-kotlin-flow-2c2454ff776e

shrimpcolo
  • 249
  • 2
  • 8
0

I would say it depends on the usecase, while using regular flow every new subscriber triggers a new flow emission this can lead to resource wastage (unnecessary network requests) on configuration change eg screen ration, if you would desire such a behaviour its okey to use regular if not consider using StateFlow. You can convert a regular flow emissions into StateFlow by using stateIn extension and set the initial state as empty as follows.

someFlow.stateIn(coroutineScope, SharingStarted.WhileSubscribed(), PagingData.empty())

According to the documentation PagingData.empty() immediately displays an empty list of items with dispatching any load state update to a presenter