[Android] Make getFromML() support cancellation

Geoffrey Métais git at videolan.org
Tue Jan 29 09:43:56 CET 2019


vlc-android | branch: master | Geoffrey Métais <geoffrey.metais at gmail.com> | Tue Jan 29 09:34:49 2019 +0100| [6d5c91b9f695e7192d0ede49b406eb3724caecb1] | committer: Geoffrey Métais

Make getFromML() support cancellation

> https://code.videolan.org/videolan/vlc-android/commit/6d5c91b9f695e7192d0ede49b406eb3724caecb1
---

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

diff --git a/vlc-android/src/org/videolan/vlc/util/Kextensions.kt b/vlc-android/src/org/videolan/vlc/util/Kextensions.kt
index f2fc4f2e5..814234c50 100644
--- a/vlc-android/src/org/videolan/vlc/util/Kextensions.kt
+++ b/vlc-android/src/org/videolan/vlc/util/Kextensions.kt
@@ -22,7 +22,6 @@ import java.net.URI
 import java.net.URISyntaxException
 import java.util.*
 import kotlin.coroutines.resume
-import kotlin.coroutines.suspendCoroutine
 
 object Settings : SingletonHolder<SharedPreferences, Context>({ PreferenceManager.getDefaultSharedPreferences(it) })
 
@@ -72,15 +71,16 @@ fun Long.random() = (Random().nextFloat() * this).toLong()
 suspend inline fun <reified T> Context.getFromMl(crossinline block: Medialibrary.() -> T) = withContext(Dispatchers.IO) {
     val ml = Medialibrary.getInstance()
     if (ml.isStarted) block.invoke(ml)
-    else suspendCoroutine { continuation ->
-        ml.addOnMedialibraryReadyListener(object : Medialibrary.OnMedialibraryReadyListener {
+    else suspendCancellableCoroutine { continuation ->
+        val listener = object : Medialibrary.OnMedialibraryReadyListener {
             override fun onMedialibraryReady() {
-                val listener = this
                 continuation.resume(block.invoke(ml))
-                launch { ml.removeOnMedialibraryReadyListener(listener) }
+                let { launch { ml.removeOnMedialibraryReadyListener(it) } }
             }
             override fun onMedialibraryIdle() {}
-        })
+        }
+        continuation.invokeOnCancellation { ml.removeOnMedialibraryReadyListener(listener) }
+        ml.addOnMedialibraryReadyListener(listener)
         startMedialibrary(false, false, false)
     }
 }



More information about the Android mailing list