@@ -698,7 +698,7 @@ 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 > {
@@ -707,7 +707,10 @@ fun main(args: Array<String>) = runBlocking<Unit> {
707
707
val two = async(start = CoroutineStart .LAZY ) { doSomethingUsefulTwo() }
708
708
println (" The answer is ${one.await() + two.await()} " )
709
709
}
710
- println (" Completed in $time ms" )
710
+ // some computation
711
+ one.start() // start the first one
712
+ two.start() // start the second one
713
+ println (" The answer is ${one.await() + two.await()} " )
711
714
}
712
715
```
713
716
@@ -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