Challenge 3: Cancelling a Running Coroutine — Solution import kotlinx.coroutines.* fun main() = runBlocking { var count = 0 val job = launch { while (isActive) { println("Count: ${count++}") delay(300) } } delay(1500) job.cancel() println("Cancelled") } /* Output: Count: 0 Count: 1 Count: 2 Count: 3 Count: 4 Cancelled Notes: - Expect roughly 5 prints (0 through 4) before cancellation: with a 300ms delay per iteration and cancelling after 1500ms, that's 1500 / 300 = 5 iterations that get to start before job.cancel() takes effect (exact count can vary slightly depending on timing). - while (isActive) checks whether the coroutine has been cancelled at the top of each loop iteration, so the loop stops cleanly on the next check after cancel() is called. - delay(300) inside the loop also independently checks for cancellation and would throw a CancellationException if the coroutine were cancelled while it was suspended there — so the loop would stop even without the explicit isActive check, just less predictably as to exactly where. */