Skip to content

Instantly share code, notes, and snippets.

@PhilippeBoisney
Last active February 12, 2019 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhilippeBoisney/b0736876850435777f00b2efeceb217e to your computer and use it in GitHub Desktop.
Save PhilippeBoisney/b0736876850435777f00b2efeceb217e to your computer and use it in GitHub Desktop.
class UserDataSource(private val repository: UserRepository,
private val query: String,
private val sort: String,
private val scope: CoroutineScope): PageKeyedDataSource<Int, User>() {
// FOR DATA ---
private var supervisorJob = SupervisorJob()
//...
// OVERRIDE ---
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, User>) {
// ...
executeQuery(1, params.requestedLoadSize) {
callback.onResult(it, null, 2)
}
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, User>) {
val page = params.key
// ...
executeQuery(page, params.requestedLoadSize) {
callback.onResult(it, page + 1)
}
}
override fun invalidate() {
super.invalidate()
supervisorJob.cancelChildren() // Cancel possible running job to only keep last result searched by user
}
// UTILS ---
private fun executeQuery(page: Int, perPage: Int, callback:(List<User>) -> Unit) {
// ...
scope.launch(getJobErrorHandler() + supervisorJob) {
delay(200) // To handle user typing case
val users = repository.searchUsersWithPagination(query, page, perPage, sort)
// ...
callback(users)
}
}
private fun getJobErrorHandler() = CoroutineExceptionHandler { _, e ->
Log.e(UserDataSource::class.java.simpleName, "An error happened: $e")
networkState.postValue(NetworkState.FAILED)
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment