https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

Remy Benza

10/28/2020, 8:27 AM
I have a question about retriggering a flow (Android app with Paging 3)
This is my code inside the viewmodel, it uses a Paging 3 PagingSource to fetch played tracks from the API in pages
Copy code
val playedTracksAsFlow: Flow<PagingData<TrackListItem>> = Pager(PagingConfig(pageSize = 20)) {
        PlayedTracksPagingSource(playedTracksRepository, epochAsZonedDateTime.value!!)
    }
            .flow
            .cachedIn(viewModelScope)

}
In the activity:
Copy code
lifecycleScope.launch {
        playedTracksViewModel.playedTracksAsFlow.collectLatest { pagingData: PagingData<TrackListItem> ->
            val pagingDataWithHeaders = pagingData.insertSeparators { trackListItem, trackListItem2 ->
                val before = (trackListItem as? NowPlaying)
                val after = (trackListItem2 as? NowPlaying)
                if (before?.until?.hour != after?.from?.hour) {
                    after?.from?.let {
                        NowPlayingHeader(it.toLocalTime())
                    }
                } else {
                    null
                }
            }
            playedTracksAdapter.submitData(pagingDataWithHeaders)
        }
    }
}
I add headers to the list, but the user needs to be able to select a different date via the date picker. Then there basically should be a whole new flow contained the tracks from the 24hours on the selected date.
Screenshots:
How should I collect a new flow from a different date?
This is my paging source:
Copy code
class PlayedTracksPagingSource(private val playedTracksRepository: PlayedTracksRepository,
                               private val initialEndDate: ZonedDateTime) : PagingSource<ZonedDateTime, TrackListItem>() {


    override suspend fun load(params: LoadParams<ZonedDateTime>): LoadResult<ZonedDateTime, TrackListItem> {
        return try {
            val userEndDate = params.key ?: initialEndDate
            val prevKey = if (ZonedDateTime.now().isAfter(userEndDate.plusHours(3))) userEndDate.plusHours(3) else null
            val nextKey = if (ZonedDateTime.now().isAfter(userEndDate.plusHours(3))) userEndDate.plusHours(3) else null // todo
            val response = playedTracksRepository.getPlayedTracks(userEndDate.minusHours(3), userEndDate)
            LoadResult.Page(
                    data = response,
                    prevKey = prevKey,
                    nextKey = userEndDate.minusHours(3)
            )

        } catch (e: IOException) {
9 Views