Skip to content
Snippets Groups Projects
Commit 875376d4 authored by Nicolas Pomepuy's avatar Nicolas Pomepuy
Browse files

Add a new waitForML method to block the current coroutine while ML init

parent cb877634
No related branches found
No related tags found
1 merge request!1128Wait for the medialibrary to be ready before launching the paged queries
......@@ -11,6 +11,11 @@ import java.io.File
import kotlin.coroutines.resume
/**
* Allows getting a ready medialibrary to query it.
* @param block: the unit to invoke when the medialibrary is ready
*/
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
suspend inline fun <reified T> Context.getFromMl(crossinline block: Medialibrary.() -> T) = withContext(Dispatchers.IO) {
val ml = Medialibrary.getInstance()
......@@ -36,6 +41,33 @@ suspend inline fun <reified T> Context.getFromMl(crossinline block: Medialibrary
}
}
/**
* Blocks the current coroutine while the medialibrary is not ready.
* Useful when we know the medialibrary init has been launched,
* we already have an instance of it and we want to wait that it's ready to query it
*/
@ExperimentalCoroutinesApi
suspend inline fun waitForML() = withContext(Dispatchers.IO) {
val ml = Medialibrary.getInstance()
if (!ml.isStarted){
suspendCancellableCoroutine<() -> Unit> { continuation ->
val listener = object : Medialibrary.OnMedialibraryReadyListener {
override fun onMedialibraryReady() {
val cb = this
if (!continuation.isCompleted) launch(start = CoroutineStart.UNDISPATCHED) {
continuation.resume {}
yield()
ml.removeOnMedialibraryReadyListener(cb)
}
}
override fun onMedialibraryIdle() {}
}
continuation.invokeOnCancellation { ml.removeOnMedialibraryReadyListener(listener) }
ml.addOnMedialibraryReadyListener(listener)
}
}
}
fun Context.startMedialibrary(firstRun: Boolean = false, upgrade: Boolean = false, parse: Boolean = true, removeDevices:Boolean = false, coroutineContextProvider: CoroutineContextProvider = CoroutineContextProvider()) = AppScope.launch {
if (Medialibrary.getInstance().isStarted || !canReadStorage(this@startMedialibrary)) return@launch
val prefs = withContext(coroutineContextProvider.IO) { Settings.getInstance(this@startMedialibrary) }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment