pull/36/head
kunfei 5 years ago
parent cde3bcf0cb
commit 86a99da671
  1. 5
      app/src/main/java/io/legado/app/base/BaseViewModel.kt
  2. 9
      app/src/main/java/io/legado/app/help/coroutine/Coroutine.kt

@ -19,7 +19,7 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio
fun <T> execute(
scope: CoroutineScope = this,
context: CoroutineContext = scope.coroutineContext.plus(Dispatchers.IO),
context: CoroutineContext = Dispatchers.IO,
block: suspend CoroutineScope.() -> T
): Coroutine<T> {
return Coroutine.async(scope, context) { block() }
@ -27,9 +27,10 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio
fun <R> submit(
scope: CoroutineScope = this,
context: CoroutineContext = Dispatchers.IO,
block: suspend CoroutineScope.() -> Deferred<R>
): Coroutine<R> {
return Coroutine.async(scope) { block().await() }
return Coroutine.async(scope, context) { block().await() }
}
@CallSuper

@ -7,7 +7,7 @@ import kotlin.coroutines.CoroutineContext
class Coroutine<T>(
scope: CoroutineScope,
context: CoroutineContext = scope.coroutineContext.plus(Dispatchers.IO),
context: CoroutineContext = Dispatchers.IO,
block: suspend CoroutineScope.() -> T
) {
@ -17,7 +17,7 @@ class Coroutine<T>(
fun <T> async(
scope: CoroutineScope = DEFAULT,
context: CoroutineContext = scope.coroutineContext.plus(Dispatchers.IO),
context: CoroutineContext = Dispatchers.IO,
block: suspend CoroutineScope.() -> T
): Coroutine<T> {
return Coroutine(scope, context, block)
@ -117,7 +117,7 @@ class Coroutine<T>(
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<T>(
}
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()

Loading…
Cancel
Save