Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a coroutine inside of a lambda

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?

like image 244
Johann Avatar asked May 20 '26 11:05

Johann


1 Answers

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!

like image 93
aleien Avatar answered May 23 '26 17:05

aleien