article banner

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.