Blog Infos
Author
Published
Topics
, ,
Published
@Composable
fun TimerScreen() {
val scope = rememberCoroutineScope()
Column {
Button(onClick = {
println("Timer started")
scope.launch {
try {
startTimer(5000) {
println("Timer ended")
}
} catch (ex: Exception) {
println("Timer cancelled")
}
}
}) {
Text("Start Timer")
}
}
}
Manual Cancellation
@Composable
fun TimerScreen() {
val scope = rememberCoroutineScope()
var job: Job? by remember {
mutableStateOf(null)
}
Column {
Button(onClick = {
job = scope.launch {
try {
println("Timer started")
startTimer(5000) {
println("Timer ended")
}
} catch (ex: Exception) {
println("timer cancelled")
}
}
}) {
Text("Start Timer")
}
Spacer(Modifier.height(20.dp))
Button(onClick = {
println("Cancelling timer")
job?.cancel()
}) {
Text("Cancel Timer")
}
}
}

Job Offers

Job Offers


    Developer (m/w/d) Backend/ Mobile

    Payback GmbH
    Cologne, Germany
    • Full Time
    apply now

    Lead Android Engineer

    ASOS
    London
    • Full Time
    apply now

    Senior Android Engineer – Big Release Team

    Zalando SE
    Berlin
    • Full Time
    apply now
Load more listings

OUR VIDEO RECOMMENDATION

Jobs

@Composable
fun TimerScreen() {
val scope = rememberCoroutineScope()
Column {
Button(onClick = {
scope.launch {
try {
println("Timer started")
startTimer(5000) {
println("Timer ended")
}
} catch (ex: Exception) {
println("Timer cancelled")
}
}
}) {
Text("Start Timer")
}
Spacer(Modifier.height(20.dp))
Button(onClick = {
println("Cancelling timer")
scope.cancel()
}) {
Text("Cancel Timer")
}
}
}

In the above example, we are calling cancel on scope instead of job. This will cancel all coroutines which are running using this scope at once. One important thing to note here is that once you call cancel on the scope, it can no longer be used to launch more coroutines. For example, if you press the start timer button twice, two coroutines would spin up with two timers. Then press cancel, both the timers would stop. Post this, clicking on Start Timer button will not start any more coroutines because the scope it is attached to, has already been cancelled.

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
Nowadays authentication has become common in almost all apps. And many of us know…
READ MORE
blog
Collections are a set of interfaces and classes that implement highly optimised data structures.…
READ MORE
blog
Hi, today I come to you with a quick tip on how to update…
READ MORE
blog

How to animate BottomSheet content using Jetpack Compose

Early this year I started a new pet project for listening to random radio…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu