Skip to content

Instantly share code, notes, and snippets.

@juliuscanute
Created July 10, 2019 00:49
Show Gist options
  • Select an option

  • Save juliuscanute/62131f0bc77e40562069e409fe877a2d to your computer and use it in GitHub Desktop.

Select an option

Save juliuscanute/62131f0bc77e40562069e409fe877a2d to your computer and use it in GitHub Desktop.
Dictionary All Words Data Source
class DictionaryAllWordsDataSource(//...) :
PositionalDataSource<Meaning>() {
//...
override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<Meaning>) {
//...
val startPage = (params.startPosition / PAGE_SIZE) + 1
if (totalPages >= startPage) {
val words = getWordsFromPage(startPage, startPage)
if (words.isEmpty()) throw NoDataException()
callback.onResult(words)
}
//...
}
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<Meaning>) {
//...
val total = getTotalPages()
val endPage = min((params.requestedLoadSize / PAGE_SIZE), 3)
val startPage = 1
val words = getWordsFromPage(startPage, endPage)
if (words.isEmpty()) throw NoDataException()
callback.onResult(words, 0, (total.end * PAGE_SIZE))
totalPages = total.end
//...
}
fun getWordsFromPage(startPage: Int, endPage: Int): MutableList<Meaning> {
val words = mutableListOf<Meaning>()
for (index in startPage..endPage) {
val dictionary = getWordsFromPage(index)
dictionary.words.forEach { words.add(it) }
}
//...
return words
}
private fun getWordsFromPage(pageNo: Int): Dictionary {
//...
return repository.getPageInDictionary(pageNo)
}
private fun getTotalPages(): Page {
//...
return repository.getNumberOfPagesInDictionary()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment