Skip to content

Instantly share code, notes, and snippets.

@avirias
Created February 21, 2022 10:36
Show Gist options
  • Save avirias/533cf2188d19c2d7d3fbd8e016398397 to your computer and use it in GitHub Desktop.
Save avirias/533cf2188d19c2d7d3fbd8e016398397 to your computer and use it in GitHub Desktop.
Query content with ease
suspend fun <T> Context.getContent(
uri: Uri,
projection: Array<String>? = null,
selection: String? = null,
selectionArgs: Array<String>? = null,
sortOrder: String? = null,
builder: Cursor.() -> T
): List<T> = suspendCancellableCoroutine { cont ->
val cancellationSignal = CancellationSignal()
try {
val list = contentResolver
.query(
uri, projection, selection, selectionArgs, sortOrder, cancellationSignal
)?.toList(builder) ?: emptyList()
cont.resume(list)
} catch (e: Exception) {
cont.resumeWithException(e)
}
cont.invokeOnCancellation {
cancellationSignal.cancel()
}
}
fun <T> Cursor.toList(
block: Cursor.() -> T,
): List<T> = use {
buildList {
while (moveToNext()) {
add(block())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment