Search code examples
hibernatekotlinkotlinx.coroutines

Load several JPA entities using Kotlin coroutine


I am trying to load several entities using Hibernate and Kotlin coroutine in application layer. Doing something like this.

fun load() : SomeData {

    val steps = someFunctionCallToGetSteps()

    val stepCollection : List<Step> = MutableList()

    runBlocking {

        for (step in steps) {

            val s = async { getStepData(step) }
            payers.add(s.await())
        }
    }
}

private suspend fun getStepData(step : Int) : Iterable<Step> {

    return someComputation()
}

But this approach is not correct because I am using await immediately so its not async per sé. I was told to collect all deferreds and use awaitAll but I cannot find any example of it anywhere. Can this be done?


Solution

  • Finally I was able to solve this issue. I am posting answer with a hope that other might benefit from it.

    fun load() : List<Result> {
    
        val steps = someFunctionCallToGetSteps()
        val result: List<Result> = ... 
    
        runBlocking {
    
            val stepsDeferred = steps.map { async { getStepData(it) } }
    
            stepsDeferred.awaitAll().forEach { result.add(it) }
        }
    
        return result
    }
    
    private suspend fun getStepData(step : Int) : Iterable<Step> {
    
        return someComputation()
    }