Last active
February 12, 2019 14:16
-
-
Save PhilippeBoisney/b0736876850435777f00b2efeceb217e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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