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


    Android App Developer

    sipgate GmbH
    Düsseldorf, Remote
    • Full Time
    apply now

    Android Build Engineer

    Pinterest
    San Francisco, CA | Seattle, WA
    • Full Time
    apply now

    Senior Mobile Systems SDK Engineer

    Sauce Labs
    Remote
    • 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
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
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

Leave a Reply

Your email address will not be published.

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

Menu