|
| 1 | +import kotlinx.coroutines.* |
| 2 | +import kotlinx.coroutines.flow.* |
| 3 | + |
| 4 | +//sampleStart |
| 5 | +// More than 50% of professional developers who use coroutines |
| 6 | +// report increased productivity |
| 7 | +// (based on Google's internal data) |
| 8 | + |
| 9 | +fun main() = runBlocking { |
| 10 | + val start = System.currentTimeMillis() |
| 11 | + coroutineScope { // Create a scope for coroutines |
| 12 | + val waitingJob = launch { // Launching a coroutine |
| 13 | + waiting(start, 150) |
| 14 | + } |
| 15 | + countdownSignals(10, 300).collect { value -> // Collecting flow elements |
| 16 | + log(start, "Countdown: $value") |
| 17 | + } |
| 18 | + waitingJob.cancel() // Cancelling a coroutine |
| 19 | + } |
| 20 | + log(start, "Liftoff!") // Execution continues when all |
| 21 | +} // coroutines have finished |
| 22 | +//sampleEnd |
| 23 | +fun countdownSignals(n: Int, delayMillis: Long): Flow<Int> = flow { // Flow builder |
| 24 | + for (i in (1..n).reversed()) { |
| 25 | + delay(delayMillis) // Delay in emitting signals |
| 26 | + emit(i) // Emit the flow element |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +// A function that can be suspended and resumed later |
| 31 | +suspend fun waiting(start: Long, delayMillis: Long) { |
| 32 | + while (currentCoroutineContext().isActive) { // Check coroutine's context |
| 33 | + log(start, "Waiting...") |
| 34 | + delay(delayMillis) // Waiting concurrently |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +fun log(start: Long, msg: String) { |
| 39 | + println("$msg after ${(System.currentTimeMillis() - start)/1000F}s") |
| 40 | +} |
0 commit comments