https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
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
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
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
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 Linen
coroutines
  • s

    Sam Gammon

    12/02/2022, 8:24 PM
    😅
    r
    • 2
    • 1
  • g

    Gioele Dev

    12/04/2022, 3:09 PM
    Hi i am new in coroutines 🙂 i have a simply question.. from viewModel i get data from server with retrofit, viewModel -> useCase -> Repository... retrofit. When create coroutine i use the classic viewModelScope.launch { ... in some book i read that for network i have to use or better to use
    viewModelScope.launch( <http://Dispatchers.IO|Dispatchers.IO>)
    is it correct ?
    m
    u
    • 3
    • 8
  • h

    He

    12/05/2022, 3:00 AM
    If i have this method
    fun wait(){
        val timeout= TimeHelper.getNow() + timeoutInterval // <- part of class constructor
        if(processor.getLag() > 0){
            val currentTIme = TimeHelper.getNow() 
    
            if(currentTime >= timeout){ System.exit(42) }
            Thread.sleep(someTime)
        }
    }
    And want to use a coroutine
    runBlocking
    and
    delay
    , would it be something like
    fun wait() = runBlocking{
        launch { delayMethod() }
        if(processor.getLag() > 0){
            val currentTIme = TimeHelper.getNow() 
    
            if(currentTime >= timeout){ System.exit(42) }
        }
    }
    
    suspend fun delayMethod(){
      delay(someTime)
    }
    g
    • 2
    • 3
  • p

    Patrick Steiger

    12/06/2022, 2:41 AM
    What’s currently the best way to check for cancellation inside a suspend fun ?
    coroutineScope { ensureActive() }
    ?
    e
    j
    h
    • 4
    • 6
  • g

    Gioele Dev

    12/06/2022, 3:32 AM
    i' am studing Flow but i don/t have example of real use now.. ok i can use some public api but i need some continous stream to try operator, zip, merge.. etc. How can use or find some data stream.. such as a socket?
    t
    e
    • 3
    • 3
  • r

    rrva

    12/06/2022, 8:47 PM
    could you annotate a method that should not be called within a coroutine so that you get a compile-time error?
    s
    e
    o
    • 4
    • 9
  • c

    coroutinedispatcher

    12/06/2022, 9:16 PM
    Hi everyone. If I would write this method:
    suspend fun timeDifference() : Int {
       val x = System.currentTimeMillis()
       delay(5.toDuration(DurationUnit.SECONDS)
       val y = System.currentTimeMillis()
       return TimeUnit.SECONDS.ofSecond(y - x)
    }
    and then write a test for this:
    @Test
    fun test() = runTest {
       val result = timeDifference()
       advanceUntilIdle()
       printLn(result)
    }
    Is it true that the output would be inconsistent? I tried it a lot of times and it doesn’t print the “predicted result” (in this case 5 seconds) but rather some other number.
    k
    b
    • 3
    • 3
  • j

    Jeong Rok Suh

    12/07/2022, 6:07 AM
    Hi, just starting to learn Mutex in Kotlin. I have a situation where I have multiple instances of a class that will work on multiple threads. And the work is a heavy computation work that takes more than 10 seconds. I want the threads to add items to the same SynchronizedList using Mutex. The work, i.e. compute() method will be a suspendable function working as a coroutine. Should I create a single, shared Mutex instance for all instances that do the heavy work? I found an example for a single instance doing work using coroutines and the Default Dispatcher, but I am not so sure about multiple instances. Any help would be appreciated.
    s
    k
    • 3
    • 2
  • a

    Anuta Vlad Sv

    12/07/2022, 8:46 AM
    Hi! I have an inline function that is binding the state to a lifecycle owner.
    inline fun <A> Flow<A>.bindState(
        lifecycleOwner: LifecycleOwner,
        crossinline bind: suspend (A) -> Unit,
    ) =
        lifecycleOwner.lifecycleScope.launchWhenStarted {
            collect(bind)
        }
    Recently I've updated the coroutines library to 1.6.4 (from 1.5.2) and looks like
    Flow.collect(crossinline action: suspend (value: T) -> Unit)
    doesn't work with the newer version of coroutines dependencies.
    Flow.collect()
    now takes a
    FlowCollector
    functional interface argument instead of a
    suspend (T) -> Unit
    . Any suggestions of how I can still keep this as an inline function?
    s
    • 2
    • 3
  • a

    arekolek

    12/08/2022, 3:36 PM
    I'm trying to run a simple program that makes an HTTP call using retrofit but for some reason it is still running even after the call is finished and I can't figure out why It finishes after about a minute, but the call is done after a few seconds
    fun main() = runBlocking {
        val service = createFooService()
        val response = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            service.foo()
        }
        println(response)
    }
    
    interface FooService {
        @POST("foo")
        suspend fun foo(): FooResponse
    }
    
    dependencies {
        implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0")
        implementation("com.squareup.okhttp3:okhttp:4.10.0")
        implementation("com.squareup.retrofit2:retrofit:2.9.0")
        implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.4")
        implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1")
    }
    s
    r
    • 3
    • 8
  • r

    Roberto Fernandez Montero

    12/09/2022, 9:40 AM
    Hi all! I've a question more philosophy than coroutines.. Having functions that does not are declared as suspend but inside them there is a scope.launch is a good practice or is better to do the scope.launch{} outside of the function but on each method invocation so each one can decide the scope to run it? For example:
    fun start() {
            coroutineScope.launch {
                socketIoServer.startAsync()
            }
        }
    
    //Another class
    socket.start()
    or
    fun start() {
       socketIoServer.startAsync()
     }
    //Another class
    
    scope.launch{ socket.start() }
    r
    r
    s
    • 4
    • 19
  • g

    George

    12/09/2022, 11:11 AM
    I have a launch {}, which inside i execute some blocking code which is listening for a single message from a pipe. Is there a way to notify/wait when the code will be suspended at the moment it started listening on the pipe? Thanks in advance for any help.
    f
    • 2
    • 3
  • s

    Stylianos Gakis

    12/09/2022, 11:38 AM
    I got a coroutine test, where I use the
    TestScope
    provided inside the
    runTest{}
    function to pass it to a
    launchIn
    function to create a hot StateFlow. Problem is, the test this way never ends since the coroutineScope always has something to do therefore
    runTest
    times out and fails my test. I’ve “fixed” this by adding the line
    this.coroutineContext.cancelChildren()
    as the last line of my test after everything I’ve asserted was correct and so on. Is this considered okay or should I really be careful with something like this? Feels like I’m doing something in a way which doesn’t solve the root cause but patches it, but could be wrong.
    d
    • 2
    • 4
  • s

    Stylianos Gakis

    12/09/2022, 1:48 PM
    Trying to test a
    okhttp3.Authenticator
    which unfortunately isn’t suspending and I am in there using
    runBlocking
    to bridge this gap. My problem is as such: In the body of that authenticator, everything is wrapped with a
    runBlocking
    but that one in turn calls a suspending function from another service. That function in turn, calls other suspending functions which at some point are using the CoroutineContext given from TestScope.backgroundScope (Or even TestScope itself). This means that then runBlocking is waiting for that to run, and the test is hanging waiting for
    runBlocking
    to finish at the same time, not giving me an opportunity to call
    runCurrent()
    or something like that to make the coroutine actually run. I guess this brings me to the question, should I be going with an UncofinedTestDispatcher here? I am kinda scared of using that usually since I don’t have good control of what’s going on, but I don’t know if that’s the more “appropriate” way to run tests with
    runTest {}
    . I usually default to not using UnconfinedTestDispatcher unless really needed, is this a bad habit?
    f
    • 2
    • 1
  • s

    stefano

    12/09/2022, 3:55 PM
    Hi folks, I have a question as a relatively newbie in the coroutine world. I'm trying to refactor this piece of code:
    val oas = specs.map {
        async {
          try {
            client.get(it).body<OpenApiSpec>() // Ktor HTTP client
          } catch (e: ClientRequestException) {
            null
          }
        }
      }.awaitAll()
    I'd like to abstract away the exception handling, so I've tried something like this:
    suspend inline fun <reified T> HttpResponse.bodyOrNull(): T? = try {
      body()
    } catch (e: ClientRequestException) {
      null
    }
    
    val oas = specs.map {
      async {
        client.get(it).bodyOrNull<OpenApiSpec>()
      }
    }.awaitAll()
    But instead of swallowing the exceptions and returning null as in the example above, I get the exception bubbling up. I suspect I'm not yet fully understanding the exception handling model for coroutines, could anybody help shed some light? Thanks in advance. (Btw, I obtain the same result if I wrap the try/catch with
    coroutineScope
    )
    • 1
    • 1
  • j

    janvladimirmostert

    12/10/2022, 11:50 PM
    when writing a custom Dispatcher, is there a way to tell IntelliJ to not show warnings about
    Possibly blocking call in non-blocking context could lead to thread starvation
    Dispatchers.IO somehow manages to make such warnings go away, I want to make those warnings go away for my custom dispatcher too
    launch(Dispatchers.CUSTOM) {
       println(Thread.currentThread())
       Thread.sleep(5_000) <<-- warning: Possibly blocking call ...
       delay(5_000)
       println("done!!!")
    }
    r
    r
    • 3
    • 7
  • o

    Osmium

    12/11/2022, 3:48 PM
    Hi! I have a question about coroutines support while targeting Kotlin/JS platform. I just saw https://github.com/Kotlin/kotlinx.coroutines/issues/3433#issuecomment-1340924559 recently, so it means coroutines in JavaScript have been abandoned in general, and it's better to use plain `Promise`s?
    a
    s
    n
    • 4
    • 3
  • s

    spierce7

    12/11/2022, 5:04 PM
    1. Is anyone running coroutine async stack traces in production? 2. Do coroutine async stacktraces work for js?
    r
    • 2
    • 1
  • h

    Hakon Grotte

    12/12/2022, 11:07 AM
    How can I test timings of a
    Flow
    ? I am trying to do with turbine and `TestCoroutineScheduler.currentTime`:
    runTest {
      val myFlow: Flow<Int> = flow<Int> {
        (1..5).forEach {
          delay(100)
          emit(it)
        }
      }
      myFlow.test {
        repeat(5) {
          awaitItem()
          println(testScheduler.currentTime)
        }
        awaitComplete()
      }
    }
    The described approach does not work: For each run my test prints different/random values, e.g. "300,500,500,500,500 " etc. I have tried using the
    myFlow.flowOn()
    operator with both test dispatchers available.
    a
    • 2
    • 2
  • u

    ursus

    12/12/2022, 7:00 PM
    I’m a bit confused as how to download a file with retrofit (okhttp) and coroutines so I declare the api
    interface SpeedApi {
        @Streaming
        @GET
        suspend fun download(@Url url: String): Response<ResponseBody>
    }
    
    val response = speedApi.download("...")
    response.body.use {
       it.byteStream().copyTo(...)
    }
    works, but the stream copying makes that blocking, and therefore not cancellable
  • u

    ursus

    12/12/2022, 7:01 PM
    should I roll my own copying like with manual cancellation check like this?
    body.use {
        it.byteStream().use { iss ->
            var bytesCopied: Long = 0
            val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
            var bytes = iss.read(buffer)
            while (bytes >= 0 && coroutineContext.isActive) { <-------------
                ...
                bytesCopied += bytes
                bytes = iss.read(buffer)
            }
            bytesCopied
        }
    }
    I do get that cancellation is cooperative etc etc — just looking for a idiomatic-retrofit way
    y
    • 2
    • 5
  • j

    jw

    12/12/2022, 7:14 PM
    Use https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-interruptible.html
    u
    • 2
    • 45
  • r

    Ron Aharoni

    12/13/2022, 8:53 AM
    We have a case of a coroutine that stops running in a Ktor server we would like help with debugging. This happens sporadically on some of our machines. The machine doesn’t seem to lack resources (CPU / memory).
    class KafkaConsumer {
    
       private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
    
       fun onMessage(message: KafkaMessage<K, V>?) {
          print("before launch") // this always shows
          scope.launch() {
            print("in coroutine") // this stops showing sometimes
            process() // Async operation that might take a second or two but also with some small runBlocking inside
          }
       }
    
    }
    Inside of
    process
    we make use again of the IO dispatcher to make an HTTP call. Are there debugging tools / techniques we could use? Would using a separate dispatcher inside
    process
    help with isolating the problem? Thanks
    s
    s
    p
    • 4
    • 7
  • f

    franztesca

    12/13/2022, 10:03 AM
    I'm on JVM, I have two coroutines that needs to access a mutable state exclusively. I can choose between using
    synchronized
    or a
    Mutex
    . Both work. Which one should I use? On one side,
    synchronized
    can block the thread of a coroutine but it's much faster, on the other side
    Mutex
    never blocks the thread but it's slower. Is there a preferred option, in general? Thanks
    c
    • 2
    • 1
  • g

    Gordon

    12/14/2022, 9:05 AM
    If i have a SharedFlow of sealed class, can i subscribe to just specific event? If so how?
    h
    g
    • 3
    • 57
  • m

    maxmello

    12/15/2022, 4:11 PM
    Still after years of using coroutines, sometimes my brain suddenly questions itself. So probably a dumb question:
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) { new { ... } }
    I have DB code from Exposed (
    new
    entity creation) that is not suspending and has this parameter:
    init: T.() -> Unit
    , which as you can see does not allow suspension. If I now really need to call a suspended function, I would usually do so before the
    new
    block and reference the result. Now I thought, what happens if I just call
    runBlocking
    with my suspending code inside
    new
    ? Will it “block more” this way, or be the same since the
    new
    block has no suspending capabilities anyway?
    s
    p
    u
    • 4
    • 16
  • j

    jeggy

    12/16/2022, 10:25 AM
    I'm using a try/catch on a function call from a library which is doing some heavy nested and recursive coroutines with a bunch of callbacks mixed from our project and the library project and am getting this error. Is there any way for me to figure out what coroutine this is and what class is the owner of it?
    k
    r
    r
    • 4
    • 5
  • v

    Vikas Singh

    12/16/2022, 10:57 AM
    Creates a supervisor job object in an active state. Children of a supervisor job can fail independently of each other Found the above statement on the doc of supervisor job, It is quite confusing for me. Like the supervisor job is used in the context of child coroutine. "Children of a supervisor job" where in practice we use a supervisor job on the child coroutine
    s
    j
    • 3
    • 11
  • e

    Exerosis

    12/18/2022, 8:10 AM
    Why isn't this used?
    withContext(CoroutineExceptionHandler { ... }) {
    
    }
    I feel like it's a very confusing system as it is now. If I had to explain it to someone else I would say that uncaught exceptions first try to go up to parent job somehow. Otherwise they look for a CoroutineExceptionHandler falling back on system unhandled exception handler. With runBlocking be a special case that ignores CoroutineExceptionHandler despite being "root". Supervisor scope being another special case where all direct children are "root". Finally you can: CoroutineScope(CoroutineExceptionHandler {}) but it will be overwritten if you provide one to launch. What is the reason it doesn't just use the context's CoroutineExceptionHandler and have scope constructors add a default handler that delegates to system unhandled? (so every context has a CoroutineExceptionHandler and a Job) Also is withContext(currentCoroutineContext()) the same as coroutineScope at the end of the day?
  • c

    Claude Brisson

    12/18/2022, 3:02 PM
    I need to call suspendable methods from a single-threaded library. Here is the context: ktor server -> standard suspendable Ktor routing methods -> Java single threaded templating rendering -(?)-> ORM suspendable methods with result Is it safe to use runBlocking (plus async/await inside) in this context? Something like:
    suspend fun someExternalSuspendFun(): String
    
    fun returnResult(): String {
      return runBlocking {
        async {
          return@async someExternalSuspendFun()
        }.await()
      }
    }
    Is there a simpler way to do this?
    e
    k
    n
    • 4
    • 12
Powered by Linen
Title
c

Claude Brisson

12/18/2022, 3:02 PM
I need to call suspendable methods from a single-threaded library. Here is the context: ktor server -> standard suspendable Ktor routing methods -> Java single threaded templating rendering -(?)-> ORM suspendable methods with result Is it safe to use runBlocking (plus async/await inside) in this context? Something like:
suspend fun someExternalSuspendFun(): String

fun returnResult(): String {
  return runBlocking {
    async {
      return@async someExternalSuspendFun()
    }.await()
  }
}
Is there a simpler way to do this?
e

efemoney

12/18/2022, 4:07 PM
Well for one the async await is useless, you could just call the suspending fn directly inside run blocking
k

kevin.cianfarini

12/18/2022, 5:22 PM
You should not use run blocking within other suspending functions. From the docs:
Runs a new coroutine and blocks the current thread until its completion. This function should not be used from a coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.
I dont quite grok exactly what you're trying to do, but it seems like you should be either: • Communicating over channels to a separate coroutine running the single threaded templating thing, or • Using
withContext(singleThreadedDispatcher)
c

Claude Brisson

12/18/2022, 6:20 PM
@efemoney yes, thanks, it shoud work.
@kevin.cianfarini the single thread dispatcher will create a new thread, while runBlocking will not. In some cases it can be a problem to use it, but I don't think it is problematic here. If you think I should not, please explain me why.
k

kevin.cianfarini

12/18/2022, 6:48 PM
You can store the single threaded dispatcher as a variable.
val mySingleThreadedDispatcher = Executors.newFixedThreadPool(1).asCoroutineDispatcher()

...

withContext(mySingleThreadedDispatcher) { someTemplateStuff() }
Tbh it kind of sounds like you should be wrapping the API of the templating thing is a suspending interface with handles thread semantics internally.
class SuspendingTemplateThing(private val templateThing: TemplateThing) {
  private val singleThreadContext = Executors.newFixedThreadPool(1).asCoroutineDispatcher()

  suspend fun doAThing() = withContext(singleThreadContext) { templateThing.doAThing() }
}
This ensures your suspending functions are main safe.
@Claude Brisson also the docs specifically call out not using
runBlocking
from a suspend function because iirc it can cause deadlock. If the docs mention you shouldn't do it, I doubt your use case is safe from the reasons they warn against using it. Furthermore,
runBlocking
will block the current thread. If you happen to be calling the templating thing from multiple different coroutines all running on different threads (such as with
<http://Dispatchers.IO|Dispatchers.IO>
) then each runBlocking call to the templating thing would happen on more than one thread.
n

Nick Allen

12/18/2022, 11:37 PM
It's hard to tell from the description if using
runBlocking
is safe or not. The warning against using it may be accurate or this could be exactly the scenario that
runBlocking
was designed for. It really depends on what code is calling
returnResult
, the thread that it's runnng on. If
returnResult
is a callback from a Java class/library that calls its callbacks from a dedicated thread for callbacks and expects callbacks to block, then you are using
runBlocking
as intended. There is a gotcha even in the intended use-case that if it's possible for other code to post to that thread then a dispatcher could exist that posts to that thread and then you could potentially deadlock (
runBlocking
calls suspend method that uses said dispatcher that queues coroutine to thread blocked by
runBlocking
).
k

kevin.cianfarini

12/19/2022, 1:10 AM
If the non-suspending function
returnResult
above is run within a coroutine, which I believe it is since this is all happening in the context of a Ktor request, then runBlocking is not safe to use I don't believe.
n

Nick Allen

12/19/2022, 7:32 AM
Not necessarily. Consider:
// suspending wrapper of non-suspend API
suspend fun SingleThreadedClass.printStuff(getMessage: suspend () -> String) {
    suspendCoroutine { cont ->
        printStuff(
            //Using runBlocking here:
            getMessage = { runBlocking { getMessage() }},
            onDone = { cont.resume(Unit) }
        )
    }
}

class SingleThreadedClass() {
    private val executor = ThreadPoolExecutor(0, 1, 0, TimeUnit.MILLISECONDS, LinkedBlockingQueue())
    
    /**
     * Executes block on private background thread to determine what to print.
     */
    fun printStuff(getMessage: () -> String, onDone:() -> Unit) {
        executor.execute {
            println(getMessage())
            onDone()
        }
    }
}
While
runBlocking
is being used from code that is part of a coroutine, it is not being called from a thread that is part of dispatching coroutines. When the docs say "This function should not be used from a coroutine" it means that it should not be called if a suspend function is on the call-stack. When execution moves to the private executor thread, there's no coroutine on the callstack . This sort of situation where a callback is called from a private thread(pool) is exactly what
runBlocking
is intended for. I could see this sort of situation being the case depending on the details of the "Java single threaded templating rendering" but it depends.
k

kevin.cianfarini

12/19/2022, 4:05 PM
I took
Java single-threaded template rendering
to mean that the templating engine isn't thread safe and must be confined to a single thread. In your above example if the templating engine is a worker of sorts then yes, I believe you're correct, runBlocking would be fine. Regardless it seems like it might be easier to decouple these two concerns. Separately fetch the DB data and pass that data to the templating engine and you wouldn't need to worry about concurrency semantics here.
View count: 8