@@ -698,13 +698,16 @@ Note, that concurrency with coroutines is always explicit.
698
698
There is a laziness option to [ async] using an optional ` start ` parameter with a value of [ CoroutineStart.LAZY] .
699
699
It starts coroutine only when its result is needed by some
700
700
[ await] [ Deferred.await ] or if a [ start] [ Job.start ] function
701
- is invoked. Run the following example that differs from the previous one only by this option :
701
+ is invoked. Run the following example:
702
702
703
703
``` kotlin
704
704
fun main (args : Array <String >) = runBlocking<Unit > {
705
705
val time = measureTimeMillis {
706
706
val one = async(start = CoroutineStart .LAZY ) { doSomethingUsefulOne() }
707
707
val two = async(start = CoroutineStart .LAZY ) { doSomethingUsefulTwo() }
708
+ // some computation
709
+ one.start() // start the first one
710
+ two.start() // start the second one
708
711
println (" The answer is ${one.await() + two.await()} " )
709
712
}
710
713
println (" Completed in $time ms" )
@@ -717,14 +720,20 @@ It produces something like this:
717
720
718
721
``` text
719
722
The answer is 42
720
- Completed in 2017 ms
723
+ Completed in 1017 ms
721
724
```
722
725
723
726
<!-- - TEST ARBITRARY_TIME -->
724
727
725
- So, we are back to sequential execution, because we _ first_ start and await for ` one ` , _ and then_ start and await
726
- for ` two ` . It is not the intended use-case for laziness. It is designed as a replacement for
727
- the standard ` lazy ` function in cases when computation of the value involves suspending functions.
728
+ So, here the two coroutines are defined but not executed as in the previous example, but the control is given to
729
+ the programmer about when exactly to start the execution by calling [ start] [ Job.start ] on it. We first
730
+ start ` one ` , then start ` two ` , and then await for the individual coroutines to finish.
731
+
732
+ Note, that if we have called [ await] [ Deferred.await ] in ` println ` and omitted [ start] [ Job.start ] on individual
733
+ coroutines, then we would have got the sequential behaviour as [ await] [ Deferred.await ] starts the coroutine
734
+ execution and waits for the execution to finish, which is not the intended use-case for laziness.
735
+ The use-case for ` async(start = CoroutineStart.LAZY) ` is a replacement for the
736
+ standard ` lazy ` function in cases when computation of the value involves suspending functions.
728
737
729
738
### Async-style functions
730
739
0 commit comments