In this Kotlin code:
async {
lateinit var testResult: TestResult
val startTime = Date()
try {
withContext(Dispatchers.IO) {
unitTest.getTestToRunAsync()?.invoke { result ->
testResult = result
doOnTestCompleted(testInfo, testResult, startTime, Date())
}
}
} catch (exception: Exception) {
testResult = TestResult("Exception: ${exception.message}")
}
}
I want to call doOnTestCompleted, which is defined like this:
private suspend fun doOnTestCompleted(
testInfo: TestInfo,
testResult: TestResult,
startTime: Date,
endTime: Date,
copyTestResults: Boolean = true
) {
}
But I cannot call doOnTestCompleted because the lambda body where it is being called from is not a coroutine. The definition for getTestToRunAsync is:
fun getTestToRunAsync(): (suspend (testToRunAsync: (resultCallback: TestResult) -> Unit) -> Unit)? {
return this.testToRunAsync
}
How can I call doOnTestCompleted?
You can do it like this
async {
lateinit var testResult: TestResult
val startTime = Date()
try {
withContext(Dispatchers.IO) {
unitTest.getTestToRunAsync()?.invoke { result ->
testResult = result
launch { doOnTestCompleted(testInfo, testResult, startTime, Date()) }
}
}
} catch (exception: Exception) {
testResult = TestResult("Exception: ${exception.message}")
}
}
Because inside lambda you still have access to CoroutineScope from async. If this approach is not good and you elaborate more restrictions we can think it further out (:
Also if you'd tell more what are you trying to achieve maybe we can find better solution. If not, hope it helps anyway!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With