Blocking threads, suspending coroutines

Traffic congestion image from wikipedia, CC BY-SA 3.0

Blocking threads

fun findBigPrime(): BigInteger = 
BigInteger.probablePrime(4096, Random())
fun BufferedReader.readMessage(): Message? =
readLine()?.parseMessage()

Suspending coroutines

val data = awaitData() // does it block or suspend?
processData(data)

Recognizing blocking code

Suspending functions

suspend fun findBigPrime(): BigInteger = 
BigInteger.probablePrime(4096, Random())

Suspending convention

suspend fun findBigPrime(): BigInteger =
withContext(Dispatchers.Default) {
BigInteger.probablePrime(4096, Random())
}

Blocking IO to suspending

suspend fun BufferedReader.readMessage(): Message? =
withContext(Dispatchers.IO) {
readLine()?.parseMessage()
}

Conclusion

--

--

--

Project Lead for the Kotlin Programming Language @JetBrains

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

AWS EKS Integration

Transcribe clips and caption timelines within DaVinci Resolve with Simon Says

Simon Says is now natively accessible within Resolve for Macs: transcribe clips, caption timelines.

Git Branching Naming Convention: Best Practices

When Slack causes problems

Python Regular expression (or RegEx)

PooZone Test & Experience -Share $10000 Airdrops & NFT Giveaway

Integrate SwaggerHub with WSO2 API Manager in 2 Steps

How to Dockerize your Rails 6 App from Scratch

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Roman Elizarov

Roman Elizarov

Project Lead for the Kotlin Programming Language @JetBrains

More from Medium

How Kotlin includes creational design patterns in language features

Getting… rid of those missing android* source sets warnings on your KMP project

Unconfined Enums Adapter for Moshi

Kotlin for Developers — technical reviewers wanted!