Exercise: Correct mistakes with cancellation
All below code snippets contain mistakes related to cancellation. Name them and explain why they are mistakes. Write a corrected version of the code.
Function updateUser
contains four mistakes. Three are related to cancellation.
suspend fun updateUser() {
val user = readUser() // blocking
val userSettings = readUserSettings(user.id) // blocking
try {
updateUserInDatabase(user, userSettings) // suspending
} catch (e: CancellationException) {
revertUnfinishedTransactions() // suspending
}
}
Function sendSignature
contains three mistakes. Two are related to cancellation.
suspend fun sendSignature(file: File) {
try {
val content = file.readText()
val signature = calculateSignature(content)
sendSignature(signature) // suspending
} catch (e: Exception) {
println("Error while sending signature: ${e.message}")
e.printStackTrace()
} finally {
file.delete()
}
}
Function trySendUntilSuccess
contains one mistake related to cancellation.
suspend fun trySendUntilSuccess() {
var success = false
do {
try {
send()
success = true
} catch (e: Exception) {
println("Error while sending: ${e.message}")
e.printStackTrace()
}
} while (!success)
}
Once you are done with the exercise, you can check your solution here.
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.