Skip to content

Instantly share code, notes, and snippets.

@orgmir
Created August 26, 2020 08:19
Show Gist options
  • Save orgmir/05b4b0265ca63fed46f2c6496c9ad913 to your computer and use it in GitHub Desktop.
Save orgmir/05b4b0265ca63fed46f2c6496c9ad913 to your computer and use it in GitHub Desktop.
Extract list of data from a androidx.paging.PagingData object
/**
* Extracts the list of data from a PagingData object.
* Useful for testing transformations on PagingData.
*
* flowOf(PagingData.from(listOf(model)).toList() == listOf(model)
*
* When nothing else is left, Java reflection will always be there to help us out.
*/
@Suppress("UNCHECKED_CAST")
private suspend fun <T : Any> PagingData<T>.toList(): List<T> {
val flow = PagingData::class.java.getDeclaredField("flow").apply {
isAccessible = true
}.get(this) as Flow<Any?>
val pageEventInsert = flow.single()
val pageEventInsertClass = Class.forName("androidx.paging.PageEvent\$Insert")
val pagesField = pageEventInsertClass.getDeclaredField("pages").apply {
isAccessible = true
}
val pages = pagesField.get(pageEventInsert) as List<Any?>
val transformablePageDataField =
Class.forName("androidx.paging.TransformablePage").getDeclaredField("data").apply {
isAccessible = true
}
val listItems =
pages.flatMap { transformablePageDataField.get(it) as List<*> }
return listItems as List<T>
}
@MuhammadKhoshnaw
Copy link

That was useful thanks 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment