RemoteMediator's append and prepend fire too early after refresh (android)

114 views Asked by At

I am using RemoteMediator in my android compose project.

The implementation looks something like:

@OptIn(ExperimentalPagingApi::class)
class MessagesRemoteMediator(
    private val db : MessagesDB,
    private val messageService : MessageService,
    private val query : Long
) : RemoteMediator<Int, MessageDb>() {


    override suspend fun initialize(): InitializeAction {
        // checking if refresh is needed
         ...
    }


    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, MessageDb>
    ): MediatorResult {

        return try {

            val response = when (loadType) {
                LoadType.REFRESH -> {
                   
                    messageService.refreshChatMessages(query)

                }
                LoadType.PREPEND -> {
                    //add new messages to start of reversed list

                    val firstItem = state.firstItemOrNull()
                        ?: return MediatorResult.Success(endOfPaginationReached = true)

                    messageService.getNewChatMessages(firstItem.timeStamp, query)

                }
                LoadType.APPEND -> {

                    // add older messages to end of reversed list

                    val lastItem = state.lastItemOrNull()
                        ?: return MediatorResult.Success(endOfPaginationReached = true)

                    messageService.getOldChatMessages(lastItem.timeStamp, query)

                }
            }

             db.withTransaction {

                db.dao.insertNewMessages(response.map {dto ->
                    dto.toMessageDb()
                })
            }

            //Does not work without delay
            if(loadType == LoadType.REFRESH)
                delay(3000)

            MediatorResult.Success(endOfPaginationReached = response.isEmpty())

        } catch (e: Exception){
            Log.d("CHECKTAGS", e.stackTraceToString())
            MediatorResult.Error(e)
        }

    }
}

I am getting response from my server on initial refresh. And new data is inserted in Room's db. Still, prepend and append calls bump into null checks and pagination stops.

It does work if I add delay after initial refresh. Is there a problem in remote mediator's code, or issue could be with lazy column in compose function?

Update Recreating project on XML gives same result. Guess I could rely on db keys solution, described here post

Still I don't understand why lastItemOrNull() does not work. For initial population of db I do not use it. It is being called only after initial data is being saved to room.

0

There are 0 answers