Created
August 26, 2020 08:19
-
-
Save orgmir/05b4b0265ca63fed46f2c6496c9ad913 to your computer and use it in GitHub Desktop.
Extract list of data from a androidx.paging.PagingData object
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
/** | |
* 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> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That was useful thanks 🚀