From 70ca91cd08d50a89e96339f91e9cbfcd7b7a7ef5 Mon Sep 17 00:00:00 2001 From: Mygod Date: Tue, 28 Jul 2020 03:31:37 +0800 Subject: [PATCH] Prevent callback being called twice when cancelling --- mobile/build.gradle.kts | 2 +- .../be/mygod/librootkotlinx/RootServer.kt | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/mobile/build.gradle.kts b/mobile/build.gradle.kts index 175a3b82..6694b9b0 100644 --- a/mobile/build.gradle.kts +++ b/mobile/build.gradle.kts @@ -95,7 +95,7 @@ dependencies { implementation("com.takisoft.preferencex:preferencex-simplemenu:1.1.0") implementation("eu.chainfire:librootjava:1.3.0") implementation("org.jetbrains.kotlinx:kotlinx-collections-immutable:0.3.2") - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.6") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.8") testImplementation("junit:junit:4.13") androidTestImplementation("androidx.room:room-testing:$roomVersion") androidTestImplementation("androidx.test:runner:1.2.0") diff --git a/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt b/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt index 96f399bd..13efab19 100644 --- a/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt +++ b/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt @@ -475,36 +475,37 @@ class RootServer @JvmOverloads constructor(private val warnLogger: (String) -> U val commandJob = Job() cancellables[callback] = { commandJob.cancel() } defaultWorker.launch(commandJob) { - try { - val result = command.execute() - withContext(callbackWorker + NonCancellable) { output.pushResult(callback, result) } + val result = try { + val result = command.execute(); + { output.pushResult(callback, result) } } catch (e: Throwable) { - withContext(callbackWorker + NonCancellable) { output.pushThrowable(callback, e) } + { output.pushThrowable(callback, e) } } finally { cancellables.remove(callback) } + withContext(callbackWorker + NonCancellable) { result() } } } is RootCommandChannel<*> -> defaultWorker.launch { - try { + val result = try { coroutineScope { command.create(this).also { cancellables[callback] = { it.cancel() } }.consumeEach { result -> withContext(callbackWorker) { output.pushResult(callback, result) } } - } - @Suppress("BlockingMethodInNonBlockingContext") - withContext(callbackWorker + NonCancellable) { + }; + @Suppress("BlockingMethodInNonBlockingContext") { output.writeByte(CHANNEL_CONSUMED) output.writeLong(callback) output.flush() } } catch (e: Throwable) { - withContext(callbackWorker + NonCancellable) { output.pushThrowable(callback, e) } + { output.pushThrowable(callback, e) } } finally { cancellables.remove(callback) } + withContext(callbackWorker + NonCancellable) { result() } } is Shutdown -> break@loop else -> throw IllegalArgumentException("Unrecognized input: $command")