5

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)
        }
    }
}

1 Answer 1

10

You've written your method as:

fun getCourses(primaryCategory: String): Flow<PagingData<CourseData>> =
    courseDataRepository.getCourses(primaryCategory).cachedIn(viewModelScope)

That means that every time this method is called, you return a brand new Flow you've called cachedIn on - you aren't actually saving that Flow anywhere at your ViewModel layer, so every time your screen recomposes or when you return to that screen, you get a brand new Flow.

Instead, you need to:

  1. Keep your primaryCategory state in your ViewModel. Expose a setter so your UI can set the category you are looking for.
  2. Use that primaryCategory state as the input into your call to courseDataRepository.getCourses
  3. Expose that final state to your UI using cachedIn to ensure that you are always returning a single Flow object that keeps cached data over a config change.

This would mean your ViewModel looks more like:

class CoursesViewModel(
    private val courseDataRepository: CourseDataRepository
): ViewModel() {
  // Keep your internal state as an observable MutableStateFlow
  // here defaulting to null
  private val primaryCategoryFlow = MutableStateFlow<String?>(null)

  // Allow your UI to change the primary category
  public fun setPrimaryCategory(primaryCategory: String) {
    primaryCategoryFlow.value = primaryCategory
  }

  // Transform each output of primaryCategoryFlow into a
  // new Flow from the courseDataRepository
  public val coursesFlow: Flow<PagingData<CourseData>> = primaryCategoryFlow
      .filterNotNull() // Skip our default value
      .distinctUntilLatest() // Don't return a new value if the category hasn't changed
      .flatMapLatest { primaryCategory ->
          courseDataRepository.getCourses(primaryCategory)
      }.cachedIn(viewModelScope)
}

And your Composable changes to set the primary category and use the new, now actually cached Flow:

if (coursesParam != null) {
  coursesViewModel.setPrimaryCategory(coursesParam)
}
val courseItems: LazyPagingItems<CourseData> =
        coursesViewModel.coursesFlow.collectAsLazyPagingItems()

You haven't included where you get your coursesParam from though - if it is an argument to one of the Navigation Compose written screens of your app, then it would also be directly available to your ViewModel via a SavedStateHandle parameter, which would allow you to read it directly from there via savedStateHandle.getStateFlow<String>("COURSES_PARAM") (e.g., using whatever key you use when creating that argument) rather than needing a setPrimaryCategory method at all.

3
  • Thanks for the code explanation, @ianhanniballake. Yes, the coursesParam is a navigation argument. Apr 9 at 2:01
  • Sounds like the SavedStateHandle way of getting that would certainly be cleaner than having to parse it in your composable and pass it to the ViewModel then! Apr 9 at 2:23
  • Yes, I am following that route, but trying to figure out how to achieve that. I am somehow a newbie in this. Thanks for the help @ianhanniballake. Apr 9 at 3:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.