优化
This commit is contained in:
@@ -2,7 +2,6 @@ package io.legado.app.help.coroutine
|
|||||||
|
|
||||||
import io.legado.app.utils.printOnDebug
|
import io.legado.app.utils.printOnDebug
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.CompletableDeferred
|
|
||||||
import kotlinx.coroutines.CompletionHandler
|
import kotlinx.coroutines.CompletionHandler
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.CoroutineStart
|
import kotlinx.coroutines.CoroutineStart
|
||||||
@@ -26,7 +25,7 @@ import kotlin.coroutines.CoroutineContext
|
|||||||
class Coroutine<T>(
|
class Coroutine<T>(
|
||||||
val scope: CoroutineScope,
|
val scope: CoroutineScope,
|
||||||
context: CoroutineContext = Dispatchers.IO,
|
context: CoroutineContext = Dispatchers.IO,
|
||||||
startOption: CoroutineStart = CoroutineStart.DEFAULT,
|
val startOption: CoroutineStart = CoroutineStart.DEFAULT,
|
||||||
val executeContext: CoroutineContext = Dispatchers.Main,
|
val executeContext: CoroutineContext = Dispatchers.Main,
|
||||||
block: suspend CoroutineScope.() -> T
|
block: suspend CoroutineScope.() -> T
|
||||||
) {
|
) {
|
||||||
@@ -58,9 +57,6 @@ class Coroutine<T>(
|
|||||||
private var timeMillis: Long? = null
|
private var timeMillis: Long? = null
|
||||||
private var errorReturn: Result<T>? = null
|
private var errorReturn: Result<T>? = null
|
||||||
|
|
||||||
private val lazyWaiter =
|
|
||||||
if (startOption === CoroutineStart.LAZY) CompletableDeferred<Unit>() else null
|
|
||||||
|
|
||||||
val isCancelled: Boolean
|
val isCancelled: Boolean
|
||||||
get() = job.isCancelled
|
get() = job.isCancelled
|
||||||
|
|
||||||
@@ -160,16 +156,19 @@ class Coroutine<T>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun start() {
|
fun start() {
|
||||||
lazyWaiter?.complete(Unit)
|
if (startOption === CoroutineStart.LAZY && isCancelled) {
|
||||||
|
cancel()
|
||||||
|
} else {
|
||||||
|
job.start()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun executeInternal(
|
private fun executeInternal(
|
||||||
context: CoroutineContext,
|
context: CoroutineContext,
|
||||||
block: suspend CoroutineScope.() -> T
|
block: suspend CoroutineScope.() -> T
|
||||||
): Job {
|
): Job {
|
||||||
return (scope.plus(executeContext)).launch(start = CoroutineStart.ATOMIC) {
|
return (scope.plus(executeContext)).launch(start = startOption) {
|
||||||
try {
|
try {
|
||||||
lazyWaiter?.await()
|
|
||||||
start?.let { dispatchVoidCallback(this, it) }
|
start?.let { dispatchVoidCallback(this, it) }
|
||||||
ensureActive()
|
ensureActive()
|
||||||
val value = executeBlock(this, context, timeMillis ?: 0L, block)
|
val value = executeBlock(this, context, timeMillis ?: 0L, block)
|
||||||
|
|||||||
Reference in New Issue
Block a user