Created
August 3, 2018 06:53
-
-
Save sharmadhiraj/0c5ef5568a79020e979e3e7109a55be9 to your computer and use it in GitHub Desktop.
Android Paging Library
This file contains 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 NewsDataSource( | |
private val networkService: NetworkService, | |
private val compositeDisposable: CompositeDisposable) | |
: PageKeyedDataSource<Int, News>() { | |
var state: MutableLiveData<State> = MutableLiveData() | |
private var retryCompletable: Completable? = null | |
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, News>) { | |
updateState(State.LOADING) | |
compositeDisposable.add( | |
networkService.getNews(1, params.requestedLoadSize) | |
.subscribe( | |
{ response -> | |
updateState(State.DONE) | |
callback.onResult(response.news, | |
null, | |
2 | |
) | |
}, | |
{ | |
updateState(State.ERROR) | |
setRetry(Action { loadInitial(params, callback) }) | |
} | |
) | |
) | |
} | |
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, News>) { | |
updateState(State.LOADING) | |
compositeDisposable.add( | |
networkService.getNews(params.key, params.requestedLoadSize) | |
.subscribe( | |
{ response -> | |
updateState(State.DONE) | |
callback.onResult(response.news, | |
params.key + 1 | |
) | |
}, | |
{ | |
updateState(State.ERROR) | |
setRetry(Action { loadAfter(params, callback) }) | |
} | |
) | |
) | |
} | |
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, News>) { | |
} | |
private fun updateState(state: State) { | |
this.state.postValue(state) | |
} | |
fun retry() { | |
if (retryCompletable != null) { | |
compositeDisposable.add(retryCompletable!! | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe()) | |
} | |
} | |
private fun setRetry(action: Action?) { | |
retryCompletable = if (action == null) null else Completable.fromAction(action) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment