kotlinkotlin-coroutinessuspend

How to wait for suspend function to be completed before executing other code in kotlin


I'm wondering if I can wait until a suspend function has completed before executing other code? loadParticlesWithoutSetCall, which I call inside of setParticlePicking, has a suspend function. I do not want anything else in setParticlePicking to be called until the suspend function has finished. Please let me know.

fun setParticlePicking(particlePicking: ParticlePicking) {
    loadParticlesWithoutSetCall()

    manualParticleMarkers?.forEach {
        imageContainerElem.remove(it)
    }
    currentParticlePicking = particlePicking
    manualParticleMarkers = (particlePicking.pickings [imageID]?.map {
        val marker = ManualParticleMarker(it.x, it.y, image = imageElem, trueHeight = particlesDat!!.imageHeight, trueWidth = particlesDat!!.imageWidth, h = particlesDat!!.h(0), w = particlesDat!!.w(0), parentElem = this@ParticlesImage.imageContainerElem)
        imageContainerElem.add(marker)
        marker
    }?: mutableListOf()) as MutableList<ManualParticleMarker>
    placeMarkers()
}



fun loadParticlesWithoutSetCall() {
    AppScope.launch {
        // clear everything
        particlesElem.removeAll()


        // load the particles
        val loadingElem = particlesElem.loading("Fetching particles ...")
        val particles: ParticlesData? = try {
            loader()
        } catch (t: Throwable) {
            errorMessage(t)
            null
        } finally {
            particlesElem.remove(loadingElem)
            toWait = true
        }

        particlesDat = particles
    }
}

Solution

  • Mark both functions suspending functions by adding the suspend modifier before fun. Then move the AppScope.launch {} call to wrap the call to setParticlePicking, wherever it is (you did not include in the sample).

    It should look something like this:

    AppScope.launch {
        setParticlePicking(particlePicking)
    }
    

    Since you will have removed the AppScope.launch {} call from loadParticlesWithoutSetCall, setParticlePicking will wait for its code to complete before moving on with the rest of the code, because suspending functions are sequential by default.