Created
February 21, 2022 10:36
-
-
Save avirias/533cf2188d19c2d7d3fbd8e016398397 to your computer and use it in GitHub Desktop.
Query content with ease
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
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