Data not dispatched when using Coroutines with Paging Library
Asked Answered
C

0

6

I want to use the Paging Library and I'm getting the data from a network call using coroutines. I've verified the data is retrieved correctly from the server but then when I call the callback from the method loadInitial I get nothing on the observed LiveData. I've tried "mocking" the server (to avoid using coroutines) and it delivers the result to the Fragment.

When I use the coroutines I first get a result on the observer of size 0 and then when the network call is completed and the callback is used I don't get anything. The problem seems to be the way I have configured the coroutine.

Is there a problem with the dispatchers used for the coroutines?

Here is the complete example of the DataSource. The CoroutineScope used is the one provided by the ViewModel.

internal class CharactersDataSource(
    private val coroutineScope: CoroutineScope,
    private val characterRepository: CharacterRepository
) : PositionalDataSource<Character>() {


    override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<Character>) {
       TODO()
    }

    override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<Character>) {
        coroutineScope.launch {
            val result = characterRepository.fetchCharacters(
                params.requestedStartPosition,
                params.requestedLoadSize
            )
            if (result is Output.Success) {
                val value = result.value
                // This next call should trigger data to be dispatched onto the LiveData
                callback.onResult(value.results, 0, value.numberResultsTotal)
            }
        }

    }
}
Crash answered 22/10, 2019 at 15:27 Comment(1)
I'm having the same issue, the data somehow magically appears when I scroll the recycler view. Let me know if you found a solution for this.Miner

© 2022 - 2024 — McMap. All rights reserved.