https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
t

tomas-mrkvička

02/04/2022, 8:46 PM
Hello guys. I am struggling with
runBlocking
. The documentation says that it should be used in
main
, tests and libraries to bridge two worlds. I found zero information about structured concurrency within plain command line applications. Lets say I have a tool which migrates data from one source to another and I would like to use concurrent executions for some parts of the whole migration process. Now, should I define
runBlocking
somewhere "in the middle", or how to use coroutines in the world where no life cycle managers exists? Thanks
n

Nick Allen

02/04/2022, 9:01 PM
runBlocking
is your lifecycle. It gives you a
CoroutineScope
as the lambda receiver to represent the lifetime of the
runBlocking
call.
runBlocking
won't return until all coroutines launched with that
CoroutineScope
have finished. For example, if you were to just call
GlobalScope.launch
then main could return and end the process before the coroutine had finished.
j

Joffrey

02/04/2022, 9:01 PM
It's totally fine to use
runBlocking
"somewhere in the middle"
👀 1
n

Nick Allen

02/04/2022, 9:04 PM
Where ever you use
runBlocking
, just avoid calling it from within a coroutine. If
runBlocking
depends on code waiting to run on threads blocked by
runBlocking
you get a deadlock.
t

tomas-mrkvička

02/04/2022, 9:10 PM
@Nick Allen That's all I have been reading in past few days. But the documentation about runBlocking usage puzzled me. @Joffrey That's what I will end up with I guess. But still thinking about other options..
j

Joffrey

02/04/2022, 9:17 PM
Yes of course don't use
runBlocking
from coroutines/suspend functions. But otherwise if the goal is to synchronously call a suspend function from the non-suspending world, it's what
runBlocking
is for. And in the context of CLI applications, this is often the case. Usually though, you can bubble up the
suspend
keyword almost all the way up to the
main
method (but you don't have to)
n

Nick Allen

02/04/2022, 9:21 PM
Use
runBlocking
anytime you want to hold up a thread until you are done with some coroutine work. So
main
is a good example. Also, synchronous callback APIs where the purpose is to allow you to do side effects, rather that to give you a result. Or if you need to implement a synchronous interface or override a synchronous method. If your caller must be synchronous but you want to use coroutines, that's where you need to use
runBlocking
.
t

tomas-mrkvička

02/04/2022, 9:28 PM
Thank you both! I will give it a try.
k

K Merle

02/05/2022, 4:58 AM
I don't think it's a good practice to call
runBlocking
half way down the pipeline. It would be easy to have a long waited suspend function easily misplaced into the
runBlocking
and have a unwanted delay in your code execution. For example, at my work we use internal authentication library that uses
runBlocking
to add authentication headers and it's causing every request to have a longer timeout then we want inside of the app, because
runBlocking
had code inside that was blocking the thread. So in general, I would avoid it.
t

tomas-mrkvička

02/05/2022, 7:57 AM
Well, than what is you recommendation? How should one deal with coroutines in the middle of the CLI app?
j

Joffrey

02/05/2022, 10:29 AM
@K Merle a library is a different animal. It's a matter of deciding whether to expose a blocking API, a suspending API, or a Future-based API. If the lib uses coroutines and expects to be used only by coroutine-based consumers, it's better to expose a suspending API. However, if you chose a blocking API for your library, you simply don't have a choice inside the lib, like in any place where the caller is blocking and expects a result synchronously. So IMO the problem is to have chosen a blocking API in the first place. Why do you think the problem in your lib is
runBlocking
? If the library takes a long time to compute those headers, and exposes a blocking API for it that guarantees the work is done when it returns, you'll have to wait and block the caller thread anyway. It could be using something entirely different, not even coroutines, and the result would be the same.
k

K Merle

02/05/2022, 11:53 AM
@tomas-mrkvička I don't have any suggestions beside that one. Could possibly execute it not in the middle. @Joffrey Problem was the underlying API (library) that generates headers and was executed in
runBlocking
, not the
runBlocking
itself. It was misused.
j

Joffrey

02/05/2022, 12:05 PM
So your application was calling an internal authentication library that was exposing a blocking API, using
runBlocking
inside, and calling a third-party library within
runBlocking
. Is this correct? Was that third-party library exposing a blocking API?
k

K Merle

02/05/2022, 1:16 PM
Internal library was having a connection timeout, and if there was no network connection it would hold a network request for couple of seconds, and we needed an error right away.
l

lhwdev

02/06/2022, 11:51 PM
Note that there are good ones to bridge from suspending to blocking functions, like
<http://Dispatchers.IO|Dispatchers.IO>
and
runInterruptible
.
runInterruptible
helps translating cancellation calls to Thread interrupt which will work for traditional java IO.
k

Klitos Kyriacou

02/13/2022, 6:18 PM
Joffrey, in your message above,
you can bubble up the 
suspend
 keyword almost all the way up to the 
main
 method
can you explain why you said "almost"?
j

Joffrey

02/14/2022, 9:14 AM
This was me being cautious, but using both "usually" and "almost" in the same sentence is unnecessary 🙂 If you have full control, you can of course even make the
main
function itself
suspend
. I was cautious because if you use some framework, maybe you don't have access to
main
, or
main
may just call the framework (which you don't control), which in turn calls you through interfaces or classes in a blocking way. When in this situation, your "entrypoint" because something else than
main
and so you may not be able to make that one
suspend
(let alone go all the way up to
main
with
suspend
functions) - but you can use
runBlocking
there, that's what it's for
✔️ 1