0

I am working on Paging 3 library and facing a issue which is like in my PagingSource class my load(params: LoadParams) returns the value before I get the response from API. I have added callback for the API response but still I am facing the same problem.

Any hack on how to solve this?

class FeedDatasource(var application: FeedActivity) :
    PagingSource<Int, FeedModel.Success_data>(), APICallback {

 override suspend fun load(params: LoadParams<Int>): LoadResult<Int, FeedModel.Success_data> {
        return try {
            // Start refresh at page 1 if undefined.
            nextPage = params.key ?: 1
            getFeedsData(params)
            LoadResult.Page(
                data = feedModel.success_data!!,
                prevKey = if (nextPage == 1) null else nextPage - 1,
                nextKey = nextPage + 1
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
      }
    }

    // APICallback override method
    override fun success(response: MutableLiveData<JsonElement>) {
        response.observe(application, { jsonElement ->
            feedModel = Gson().fromJson(jsonElement, FeedModel::class.java)
        })
    }



fun getFeedsData(params: LoadParams<Int>) {
        val nextPage = params.key ?: 1
        if (nextPage <= feedModel.total_page!!) {
            UserRepository.callAPI(
                getJsonObject(nextPage),
                AppConstants.APIMarks.FEED_LIST,
                AppConstants.HTTPMethod.HTTP_POST, this
            )
        }
    }




interface APICallback {

    fun success(response: MutableLiveData<JsonElement>)

    fun failure()

}
primo
  • 1,340
  • 3
  • 12
  • 40
  • 1
    You can't use callbacks here. You need to turn that callback based code into a suspend function and then call it from the `load` function. You can use `suspendCancellableCoroutine` to convert your callback code to a suspend function. – Arpit Shukla Nov 30 '21 at 11:05
  • I don't have idea about that. Can you please help me out on how to do this Arpit? – primo Nov 30 '21 at 13:05
  • I can try. Add the revelant functions in questions, like `getFeedsData`. What is `feedModel.success_data` and `APICallback`? – Arpit Shukla Nov 30 '21 at 15:07
  • I have added all the things you asked for – primo Dec 01 '21 at 06:14
  • Add code for `UserRepository.callAPI` function as well. – Arpit Shukla Dec 01 '21 at 07:04
  • It is my API call method. I have used retrfit with rxjava2 observable – primo Dec 01 '21 at 08:08
  • You are passing `this` to the `callAPI` function which I guess refers to `APICallback`. You need to make `callAPI` a suspend function. I don't have experience with rxjava so won't be able to help there but Retrofit supports suspend functions so you can mark you retrofit functions as suspend and then call them from `UserRepository.callAPI` – Arpit Shukla Dec 01 '21 at 08:16

0 Answers0