[Android] Prevent concurrent access in a more idiomatic way

Geoffrey Métais git at videolan.org
Thu Mar 14 15:46:06 CET 2019


vlc-android | branch: master | Geoffrey Métais <geoffrey.metais at gmail.com> | Thu Mar 14 15:45:27 2019 +0100| [904b705f72d22bd9119297455b5c459953bb1f9f] | committer: Geoffrey Métais

Prevent concurrent access in a more idiomatic way

> https://code.videolan.org/videolan/vlc-android/commit/904b705f72d22bd9119297455b5c459953bb1f9f
---

 vlc-android/src/org/videolan/vlc/util/Kextensions.kt | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/vlc-android/src/org/videolan/vlc/util/Kextensions.kt b/vlc-android/src/org/videolan/vlc/util/Kextensions.kt
index 027c79d0e..56262a46a 100644
--- a/vlc-android/src/org/videolan/vlc/util/Kextensions.kt
+++ b/vlc-android/src/org/videolan/vlc/util/Kextensions.kt
@@ -75,6 +75,7 @@ fun Context.getAppSystemService(name: String) = applicationContext.getSystemServ
 
 fun Long.random() = (Random().nextFloat() * this).toLong()
 
+ at ExperimentalCoroutinesApi
 suspend inline fun <reified T> Context.getFromMl(crossinline block: Medialibrary.() -> T) = withContext(Dispatchers.IO) {
     val ml = Medialibrary.getInstance()
     if (ml.isStarted) block.invoke(ml)
@@ -83,8 +84,12 @@ suspend inline fun <reified T> Context.getFromMl(crossinline block: Medialibrary
         suspendCancellableCoroutine { continuation ->
             val listener = object : Medialibrary.OnMedialibraryReadyListener {
                 override fun onMedialibraryReady() {
-                    if (!continuation.isCompleted) continuation.resume(block.invoke(ml))
-                    let { launch { ml.removeOnMedialibraryReadyListener(it) } }
+                    val cb = this
+                    if (!continuation.isCompleted) launch(start = CoroutineStart.UNDISPATCHED) {
+                        continuation.resume(block.invoke(ml))
+                        yield()
+                        ml.removeOnMedialibraryReadyListener(cb)
+                    }
                 }
                 override fun onMedialibraryIdle() {}
             }



More information about the Android mailing list