Lazy execution

Lazy execution or call-by-need is a common approach in software development. This strategy allows us to delay the evaluation of an expression until we need it. in Kotlin, coroutines also allow us to use this approach. Coroutine builders such as launch, withContext, and async contain a start: CoroutineStart parameter with the following default argument—CoroutineStart.DEFAULT.

The following example shows how to start a coroutine lazily using this parameter:

fun main(args: Array<String>) = runBlocking<Unit> {
Job().also { parentJob->
val job = launch(parent = parentJob, start = CoroutineStart.LAZY) { downloadImage() }
//.......
job.start()
}.joinChildren()
}

The job will only be started when we invoke the start method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.109.8