diff --git a/app/src/main/java/io/legado/app/base/BaseViewModel.kt b/app/src/main/java/io/legado/app/base/BaseViewModel.kt index 98e09354b..3610a00a5 100644 --- a/app/src/main/java/io/legado/app/base/BaseViewModel.kt +++ b/app/src/main/java/io/legado/app/base/BaseViewModel.kt @@ -19,7 +19,7 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio fun execute( scope: CoroutineScope = this, - context: CoroutineContext = scope.coroutineContext.plus(Dispatchers.IO), + context: CoroutineContext = Dispatchers.IO, block: suspend CoroutineScope.() -> T ): Coroutine { return Coroutine.async(scope, context) { block() } @@ -27,9 +27,10 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio fun submit( scope: CoroutineScope = this, + context: CoroutineContext = Dispatchers.IO, block: suspend CoroutineScope.() -> Deferred ): Coroutine { - return Coroutine.async(scope) { block().await() } + return Coroutine.async(scope, context) { block().await() } } @CallSuper diff --git a/app/src/main/java/io/legado/app/help/coroutine/Coroutine.kt b/app/src/main/java/io/legado/app/help/coroutine/Coroutine.kt index c61efdd23..e9fd0df86 100644 --- a/app/src/main/java/io/legado/app/help/coroutine/Coroutine.kt +++ b/app/src/main/java/io/legado/app/help/coroutine/Coroutine.kt @@ -7,7 +7,7 @@ import kotlin.coroutines.CoroutineContext class Coroutine( scope: CoroutineScope, - context: CoroutineContext = scope.coroutineContext.plus(Dispatchers.IO), + context: CoroutineContext = Dispatchers.IO, block: suspend CoroutineScope.() -> T ) { @@ -17,7 +17,7 @@ class Coroutine( fun async( scope: CoroutineScope = DEFAULT, - context: CoroutineContext = scope.coroutineContext.plus(Dispatchers.IO), + context: CoroutineContext = Dispatchers.IO, block: suspend CoroutineScope.() -> T ): Coroutine { return Coroutine(scope, context, block) @@ -117,7 +117,7 @@ class Coroutine( return scope.plus(Dispatchers.Main).launch { try { start?.let { dispatchVoidCallback(this, it) } - val value = executeBlock(context, timeMillis ?: 0L, block) + val value = executeBlock(scope, context, timeMillis ?: 0L, block) success?.let { dispatchCallback(this, value, it) } } catch (e: Throwable) { if (BuildConfig.DEBUG) { @@ -162,11 +162,12 @@ class Coroutine( } private suspend inline fun executeBlock( + scope: CoroutineScope, context: CoroutineContext, timeMillis: Long, noinline block: suspend CoroutineScope.() -> T ): T? { - return withContext(context) { + return withContext(scope.coroutineContext.plus(context)) { if (timeMillis > 0L) withTimeout(timeMillis) { block() } else block()