I am using Jetpack Compose with navigation component, Retrofit, and Paging 3. The problem I am having is that, when I navigate to the screen that has pagination, it makes 3 consecutive network requests, and when I navigate away to another screen, it makes a request again, and as a result of this, it's not caching. From performance standpoint, that is not good. I tried using LauncdedEffect
in composable, but it's throwing a compilation error. What can I do to prevent this multiple requests?
My viewModel:
class CoursesViewModel(private val courseDataRepository: CourseDataRepository): ViewModel() {
// ......
fun getCourses(primaryCategory: String): Flow<PagingData<CourseData>> =
courseDataRepository.getCourses(primaryCategory).cachedIn(viewModelScope)
// ......
}
My Repository:
interface CourseDataRepository {
// ....
fun getCourses(queryParam: String): Flow<PagingData<CourseData>>
// ....
}
class DefaultCourseDataRepository(private val retrofitService: EskoolApiService): CourseDataRepository {
// .....
override fun getCourses(queryParam: String): Flow<PagingData<CourseData>> {
return Pager(
config = PagingConfig(pageSize = PAGE_SIZE),
pagingSourceFactory = {
CourseDataSource(queryParam, retrofitService)
}
).flow
}
// .....
}
My DataSource:
class CourseDataSource(
private val queryIdentifier: String,
private val apiService: EskoolApiService
): PagingSource<Int, CourseData>() {
override fun getRefreshKey(state: PagingState<Int, CourseData>): Int? {
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
}
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, CourseData> {
return try {
val nextPage = params.key ?: 1
val filters = mapOf("page" to nextPage, "page_size" to PAGE_SIZE)
val data: Courses = if (queryIdentifier == defaultCoursesArg) {
apiService.getAllCourses(filters, null)
} else {
apiService.getAllCourses(filters, queryIdentifier)
}
LoadResult.Page(
data = data.courses,
prevKey = if (nextPage == 1) null else nextPage - 1,
nextKey = if (data.courses.isEmpty()) null else nextPage + 1
)
} catch (e: IOException) { // ************
return LoadResult.Error(e)
} catch (exception: HttpException) {
return LoadResult.Error(exception)
}
}
}
CoursesScreen
@SuppressLint("MutableCollectionMutableState")
@Composable
fun CoursesScreen(
modifier: Modifier = Modifier,
coursesViewModel: CoursesViewModel,
coursesParam: String? = defaultCoursesArg,
onClickCourseDetailsBySpan: (Int) -> Unit = {},
onClickCourseDetailsByTitle: (Int) -> Unit = {},
) {
val courseItems: LazyPagingItems<CourseData> =
coursesViewModel.getCourses(coursesParam!!).collectAsLazyPagingItems()
Surface(
modifier = modifier
.padding(vertical = CARD_PADDING),
color = colors.background
) {
CourseCards(
courses = courseItems,
onClickCourseDetailsBySpan = onClickCourseDetailsBySpan,
onClickCourseTitle = onClickCourseDetailsByTitle,
)
}
}
MainActivity
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val coursesViewModel: CoursesViewModel = viewModel(factory = CoursesViewModel.Factory)
// app content
ESchoolApp(viewModel = coursesViewModel)
}
}
}