https://kotlinlang.org logo
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

    sboishtyan

    05/12/2021, 4:48 PM
    Hi everyone How could I write the code below with
    Flow
    Observable.create(
                { emitter ->
                    val process: Process = ProcessBuilder(commandAndArgs)
                        .redirectErrorStream(true)
                        .start()
    
                    emitter.setCancellation {
                        process.destroy()
                    }
            )
    So idea is that I want when someone starts collecting the flow I will create a process and when a client stops collecting I will destroy the process
    e
    • 2
    • 2
  • z

    Zach Klippenstein (he/him) [MOD]

    05/12/2021, 5:08 PM
    Anyone else noticed this bug in coroutines 1.5-RC1? Seems pretty serious, but i haven’t heard anything about it until now.
    o
    i
    s
    • 4
    • 8
  • u

    ursus

    05/13/2021, 3:51 AM
    suspend fun send(someId) {
       val currentState = db.getState(someId)
       if (currentState == null) error("Unknown id")
       if (currentState == Sent) return // idempotent
       if (currentState == Sending) .. mutex?
    
       try {
          db.setState(Sending, someId)
          api.send(..)
          db.setState(Sent, someId)
       } catch (ex) {
          db.setState(Idle, someId)
       }
    }
    This is very common pattern in apps I make. What would the idiomatic way to make this code thread/coroutine safe? Obviously, if same id ist being sent concurrently multiple times, state might get smashed Is it okay to use Mutex around the whole function? Granted, only same ids needs to be serialized -- should I then have a Map<SomeId, Mutex>? Is there maybe some conditional Mutex? Or maybe not mutex at all, and use some sort of concurrent counter as not to revert to Idle when other coroutine is Sending etc? Or some Channel magic I dont know?
    e
    • 2
    • 8
  • l

    louiscad

    05/13/2021, 4:06 AM
    Looks like
    1.5.0-RC-native-mt
    is out!
    j
    • 2
    • 2
  • k

    Karan Sharma

    05/13/2021, 11:43 AM
    https://stackoverflow.com/questions/67518481/how-to-convert-3-or-more-livedata-into-a-single-flow-in-android
    l
    r
    m
    • 4
    • 7
  • a

    Abhishek Dewan

    05/13/2021, 3:51 PM
    Hey guys, if I have something like in my application I am noticing that flow2 doesn't ever get to execute but flow 1 does however, if I change the order and put flow2 before flow1, both flows execute. Would anyone know why this could be the case? For context in my application flow1 represents a SQLDelight DB transaction where as flow2 represents a network call.
    viewModelScope.launch { 
        flow1.collect {}
        flow2.collect {}
    }
    👍 1
    j
    c
    e
    • 4
    • 5
  • d

    dan.the.man

    05/13/2021, 5:36 PM
    Hi guys, I have a weird one
    fun <T> LifecycleOwner.stateFlow(stateFlow: StateFlow<T>, funCollect: (T) -> Unit) {
            lifecycleScope.launchWhenStarted {
                stateFlow.collect() {
                    funCollect(it)
                }
            }
        }
    Is how I subscribe to a Stateflow. I then subscribe to that in my fragment. However, very infrequently, my Stateflow doesn't emit.
    Timber.d(//This log is hit)
                model.data.emit(result)
    The log above is hit, in theory I would think it should have emit, but for some reason, my subscription is never hit in my fragment. The correct object is being pushed to/observed, not sure what's happening, any thoughts?
    u
    r
    • 3
    • 15
  • c

    Colton Idle

    05/14/2021, 2:08 AM
    Really basic question here but I feel like I'm finding a lot of out of date information. How can I wait for a coroutine to finish in a test? example:
    @Test
    fun `test network call`() {
        var response: Response<Projects>
        GlobalScope.async {
            response = service.getMostPopularProjects()
        }
    
        assertThat(response.body().popularProjectSize().toString()).isGreaterThan("1")
    }
    z
    e
    • 3
    • 11
  • m

    ms

    05/14/2021, 10:07 AM
    App crashes when combining Flow with a MutableStateFlow. Code in 🧵
    n
    e
    +2
    • 5
    • 17
  • v

    Vsevolod Tolstopyatov [JB]

    05/14/2021, 3:34 PM
    📣 📣 📣 kotlinx.coroutines 1.5.0 is here! * New channels API:
    trySend
    ,
    tryReceive
    , and
    receiveCatching
    instead of error-prone
    poll
    and
    offer
    * Reactive integrations,
    callbackFlow
    , and
    channelFlow
    are promoted to stable API *
    CoroutinesTimeout
    JUnit5 rule And a lot more! Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.5.0
    😒uspend: 2
    🎉 26
    :kotlin-intensifies: 16
    🔥 1
    b
    c
    +3
    • 6
    • 8
  • y

    Yan Pujante

    05/14/2021, 5:28 PM
    I am trying to create a Flow api for
    java.lang.Process
    and although this does NOT trigger an error, the call to
    waitFor
    is flagged as inaprorriate blocking call. Is there a better way to do it? Code in thread to not pollute here...
    e
    • 2
    • 7
  • w

    wakingrufus

    05/14/2021, 7:12 PM
    what is a good way to approach debugging
    ClassCastException: kotlin.coroutines.intrinsics.CoroutineSingletons cannot be cast to ...
    I am using
    suspend fun
    as well as Flows, but I am not sure where to start with this.
    e
    b
    • 3
    • 14
  • u

    ursus

    05/16/2021, 3:09 PM
    I have a question about main-safety. I get the idea that any suspend function should be able to be called from main-thread/dispatcher scope. However, that means, what in practise? How far do you go? Every public suspend function should apply it's own withContext? Or be pragmatic, and "know" which functions will be sort-of ui related and only do it there? Another example might be "sync" routines, which are ran in a Syncer which has its own scope driven by IO dispatcher. Would you apply withContext even in some of the partial sync components?
    class Syncer(private val somePartialSyncComponentNeverRelatedToUi) {
       private val scope = CoroutineScope(<http://Dispatcher.IO|Dispatcher.IO>)
    
       fun sync() {
          scope.launch {
             somePartialSyncComponent.doWhatever()
          }
       }
    }
    
    class SomePartialSyncComponentNeverRelatedToUi {
       suspend func doWhatever {
          withContext here ??? <--------
       }
    }
    Is it not wasteful context switch?
    a
    e
    m
    • 4
    • 38
  • h

    hho

    05/17/2021, 12:48 PM
    Hi, I've just started using coroutines… I'm trying to parse JSON (with Jackson) in a
    suspend fun
    , and the "Inappropriate blocking method call" inspection flags my code:
    val message = objectMapper.readTree(inputString)
    What can I do about it? It's not doing I/O, it's operating on a String.
    y
    s
    +2
    • 5
    • 7
  • e

    efemoney

    05/17/2021, 3:09 PM
    Say I have two tasks that return the same result. How can I wait for the first of the two tasks to complete?
    e
    • 2
    • 2
  • s

    Stanley Gomes

    05/18/2021, 3:49 AM
    I want to display an image for 3 seconds while also fetching, serializing and persisting a large JSON blob. Keeping in mind the whole operation could take more than 3 seconds on slow network, this is what I have right now
    viewmodelScope.launch {
          val deferredFetchAndPersist = async {
              some suspend fun()
          }
          val deferredTimer = async {
              delay(3000)
          }
          awaitAll(deferredFetchAndPersist, deferredTimer)
    
          hideImageView()
       }
    This works but I feel it's a little too verbose. Is there a better way I can achieve this? Thanks
    e
    u
    b
    • 4
    • 9
  • p

    Pablo

    05/18/2021, 3:38 PM
    Is there any way to "throat" or "debounce" when user click on a button (in Android) to avoid multi-clicks? I've found something like this
    fun <T> debounce(
        delayMillis: Long = 300L,
        scope: CoroutineScope,
        action: (T) -> Unit
    ): (T) -> Unit {
        var debounceJob: Job? = null
        return { param: T ->
            if (debounceJob == null) {
                debounceJob = scope.launch {
                    action(param)
                    delay(delayMillis)
                    debounceJob = null
                }
            }
        }
    }
    Where I can do
    fun setDebounceListener(view: Button, onClickListener: View.OnClickListener) {
        val clickWithDebounce: (view: View) -> Unit =
            debounce(scope = MainScope()) {
                onClickListener.onClick(it)
            }
        view.setOnClickListener(clickWithDebounce)
    }
    Does it make sense to use debounce here? It's just to avoid double click on a Button
    l
    • 2
    • 99
  • s

    spierce7

    05/18/2021, 4:18 PM
    Watching the

    new video on kotlin coroutines 1.5▾

    - I’m a little confused by the description of the
    GlobalScope
    delicate api legitimate use cases. It’s my understanding that any time I would create a generic
    CoroutineScope
    , and then not cancel it, I can use
    GlobalScope
    instead. Is that correct? The main hesitation with the
    GlobalScope
    is simply that you can’t cancel it, and thus, it doesn’t lend itself well to hierarchical coroutines, right?.
    z
    s
    s
    • 4
    • 11
  • s

    spierce7

    05/18/2021, 10:24 PM
    How does the StateFlow
    .value
    work? I’m seeing instances where values are `emit`ted from the
    Flow
    , but then the
    .value
    is never updated to reflect the result that was either set on
    .value
    or
    emit
    on the
    Flow
    .
    z
    d
    • 3
    • 4
  • g

    Grantas33

    05/18/2021, 10:27 PM
    using launch(Dispatcher.Default) {..} on a single core machine causes a deadlock (app idles forever), is this expected? It would be nice to get some runtime exception
    b
    t
    r
    • 4
    • 7
  • m

    Marius Metzger

    05/19/2021, 3:13 PM
    @InternalCoroutinesApi
        override fun isDispatchNeeded(context: CoroutineContext): Boolean {
            if (Bukkit.isPrimaryThread()) return false
    
            // Check if the primary server thread is blocked during the execution of this coroutine.
            // If it is, using the Bukkit scheduler would cause a deadlock, as scheduled tasks
            // are executed at the end of the tick, which requires the server thread to be running.
    
            // To detect whether the server thread is blocked, we traverse the hierarchy of Jobs upwards
            // to check if there's a coroutine running in a [runBlocking] context.
            // If so, we don't dispatch, causing the action to be executed on the current thread.
            // As the primary thread is locked, this has no thread-safety implications with regards to
            // the Bukkit API.
            // However, Bukkit methods that check whether they're performed on the server thread,
            // such as spawning an entity, will fail exceptionally - if this becomes an issue,
            // we can move the [isDispatchNeeded] logic into [dispatch], toggling a global flag while
            // directly executing the runnable, and patch the server software to respect this flag
            // during those checks.
    
            var job: Job? = context[Job]
            while (job != null) {
                if (job.javaClass == blockingCoroutineClass) {
                    // we found a coroutine spawned via runBlocking - check whether it blocks the
                    // primary server thread using the same logic as [CraftServer.isPrimaryThread]
                    val blockedThread = Reflect.on(job).field("blockedThread").get<Thread>()
                    if (blockedThread == MinecraftServer.getServer().serverThread ||
                        blockedThread == MinecraftServer.getServer().shutdownThread ||
                        blockedThread is TickThread) {
                        return false
                    }
                }
    
                if (AbstractCoroutine::class.java.isAssignableFrom(job.javaClass)) {
                    // traverse context hierarchy upwards
                    job = Reflect.on(job).field("parentContext").get<CoroutineContext>()[Job]
                } else {
                    throw UnsupportedOperationException("Can't handle jobs of type ${job.javaClass}")
                }
            }
    
            return true
        }
    it’s not beautiful, but it worked - until I just updated to kotlinx.coroutines 1.5.0, which removes the field
    AbstractCoroutine.parentContext
    in this commit. Now my question is: is there still a way to hackily derive the parent
    Job
    from a coroutine? Or even better - is there a proper solution to this issue that doesn’t require messing with coroutine internals at all? any help is appreciated 😊
    z
    r
    a
    • 4
    • 7
  • f

    frankelot

    05/19/2021, 8:32 PM
    Hi all 👋 I have a (potentially) dumb question regarding
    CoroutineScope
    s I have a class that allocates some resources on its constructor
    init { // }
    and the client has to explicitly call
    .dispose()
    when it's done with it (I'm on Android so this is done in
    onDestroy()
    )
    lateinit var foo : Foo
    onCreate() {
      foo = Foo() // resources get allocated (init openGL context, open a file, etc)
    }
    
    onDestroy() {
      foo.dispose() // must not forget!
    }
    I was thinking that it would be really nice to have these resources cleaned up automatically (something like RAII in c++) That got me thinking, if there was a way to get a callback when the parent coroutine scope is being cancelled... I could do the cleanup then
    e
    • 2
    • 6
  • u

    ursus

    05/20/2021, 2:41 AM
    Is it leaky if I never cancel a coroutine scope, but all it's jobs are finished?
    e
    • 2
    • 2
  • d

    Dominaezzz

    05/20/2021, 11:25 AM
    Tbh, I don't like that fact that it's been marked as delicate, there are other ways to do the same discouraged thing. Maybe the coroutine scope constructor should also be marked as delicate, since one can still forget to cancel it. Then again I don't really use global scope so I don't really care that much.
    z
    • 2
    • 2
  • k

    Kirill Gribov

    05/20/2021, 12:33 PM
    hey guys! We have updated kotlin, kotlinx and ktor in our project up to versions 1.5.0 and 1.5.4. Also we decided to try new value classes in requests and responses. We deployed our changes and have faced next errors:
    l
    j
    • 3
    • 12
  • s

    sunnat629

    05/20/2021, 3:14 PM
    Hey, I am working in a non UI class [Model layer] -
    private val _program = MutableStateFlow(NwProgram())
    override val program: StateFlow<NwProgram> = _program
    
    private val stateFlowScope: CoroutineScope by lazy { CoroutineScope(Dispatchers.Default) }
    
    override val entities: StateFlow<List<NwEntity>> = program.transform {
        emit(it.entities ?: emptyList())
    }.stateIn(
        scope = stateFlowScope,
        started = WhileSubscribed(5000),
        initialValue = emptyList()
    )
    But during building, it got -
    e: java.lang.AssertionError: Unbound symbols not allowed
    
    Execution failed for task ':coresdk:compileDebugKotlin'.
    > Internal compiler error. See log for more details
    Kotlin v1.5.0
     and 
    coroutines v1.5.0
    So, why it’s happening? Can anyone help I was migrating 
    livedata
     to 
    stateflow
     in my Android project.
    y
    • 2
    • 3
  • s

    Slackbot

    05/21/2021, 9:06 AM
    This message was deleted.
    t
    m
    p
    • 4
    • 3
  • k

    Kirill Gribov

    05/21/2021, 5:14 PM
    Ok, we found the issue, it is easy to reproduce with simple code snippet -
    @JvmInline
    value class ValueClassId(private val value: UUID)
    
    class SomeService {
    
        suspend fun outerFails(id: UUID): ValueClassId {
            return inner(id)
        }
    
        suspend fun outerWorks(id: UUID) = try {
            somethingTrowing()
            justValueId(id)
        } catch (e: RuntimeException) {
            fallbackValueId(id)
        }
    
        private suspend fun inner(id: UUID) = try {
            somethingTrowing()
            justValueId(id)
        } catch (e: RuntimeException) {
            fallbackValueId(id)
        }
    
        private suspend fun justValueId(id: UUID): ValueClassId {
            delay(1)
            return ValueClassId(id)
        }
    
        private suspend fun fallbackValueId(id: UUID): ValueClassId {
            delay(1)
            return ValueClassId(id)
        }
    
        private suspend fun somethingTrowing(): Unit {
            delay(1)
            throw IllegalArgumentException()
        }
    }
    
    fun main(): Unit = runBlocking {
        val s = SomeService()
        val id = UUID.randomUUID()
    
        // works fine
        s.outerWorks(id)
    
        // Fails on: ContinuationImpl.kt:33
        // val outcome = invokeSuspend(param)
        // if (outcome === COROUTINE_SUSPENDED) return
        s.outerFails(id)
    }
    :youtrack: 1
    w
    n
    i
    • 4
    • 7
  • d

    dniHze

    05/22/2021, 4:58 PM
    Hi, I'm just wandering, why there is no
    Flow.flatMap
    operator? I know that direct replacement for it is
    Flow.flatMapMerge
    , but I'm still wandering why the team decided to avoid regular
    flatMap
    naming for particular operator in a favor of, well, a longer and more self-describing name. For me it's kinda weird trying to name basically the same thing differently, especially from the common to other libraries and languages perspective. Not trying to convince anybody to rename the operator, just searching for the reasoning.
    d
    o
    c
    • 4
    • 7
  • j

    Jimmy Alvarez

    05/22/2021, 11:04 PM
    Hi guys, hope you are doing well. Sorry for this noob question, I’m trying to understand the concurrency concepts when using coroutines. My questions is, is it posible to execute concurrently a couple of suspending functions in the same coroutine?
    s
    e
    +2
    • 5
    • 14
Powered by Linen
Title
j

Jimmy Alvarez

05/22/2021, 11:04 PM
Hi guys, hope you are doing well. Sorry for this noob question, I’m trying to understand the concurrency concepts when using coroutines. My questions is, is it posible to execute concurrently a couple of suspending functions in the same coroutine?
s

streetsofboston

05/22/2021, 11:39 PM
Yup, absolutely. Call 'launch' or 'async' a bunch of times on the same CoroutineScope and call your suspending functions inside these 'launch/'async' calls.
j

Jimmy Alvarez

05/22/2021, 11:48 PM
But, what if launch or async runs on a Main Dispatcher where there is only one thread available?
s

streetsofboston

05/23/2021, 12:12 AM
Since suspend functions are not blocking (are yours blocking?), they can still run asynchronously (although not parallel)
j

Jimmy Alvarez

05/23/2021, 12:42 AM
Do you mean with (although not parallel) is that this will be sequenced one behind other suspend but you do not control when they completes. For me this looks like blocking
scope.launch(onlyOneThreadDispatcher) {
    suspendFunc1()
    suspendFunc1()
}
This will be blocking, does not will?
e

ephemient

05/23/2021, 2:17 AM
launch { suspend1() }; launch { suspend2()
may run interleaved at suspend points even if the executor only has one thread. that's kinda the whole point?
☝️ 1
s

streetsofboston

05/23/2021, 3:49 AM
scope.launch { suspendFunc1() }
scope.launch { suspendFunc2() }
More like the above. The calls to launch return immediately and the two suspendFuncs run asynchronously. In your example, Jimmy, where they are called inside the same one launch call, they run sequentially. But, sequentially or asynchronously, they are never blocking. They are suspending. Unless you put actual blocking code inside of them (eg Thread.sleep() or waiting for a socket, etc)
d

diesieben07

05/23/2021, 9:12 AM
All of the above create new coroutines though.
launch
starts a new coroutine. So technically the answer is: No, one coroutine only ever executes one suspending function at a time. However coroutines are cheap, so you can just launch as many as you need.
e

Erik

05/23/2021, 3:55 PM
You're right, Take, but the new coroutines are child coroutines in the parent's scope. So, if it helps to understand the concept, you can imagine the children as running and suspending concurrently when viewed from the parent, if they don't block all the scope's resources (e.g. if it has 1 thread and makes a blocking instead of suspending call). What you're saying essentially is right and means that a coroutine can only run things sequentially (if it doesn't do classic threading), but it has the ability to suspend and launch (fork) other coroutines. In itself it doesn't run things in parallel, but it does have the power to be running in parallel, or have children run in parallel.
j

Jimmy Alvarez

05/24/2021, 2:32 PM
I think i have doubts about suspending and blocking code, for me makes sense what Take Weiland said. In the example i put above, lets say
suspendFunc1()
function is a remote call, in my understanding
suspendFunc2()
will not be executed until remote call completes, even if it is
suspend
So, even if the function is suspend it is blocking the coroutine, isn’t it?
Thanks in advance for you replies, makes a lot easier my understanding!!!!!
e

Erik

05/24/2021, 3:55 PM
Yes in your example the first suspending call runs and has to complete before the second suspending call. That's not what you call blocking, that's just sequential code: the first goes before the second. Because the first is marked with the
suspend
modifier, it indicates that the function might suspend while running (e.g. of it is awaiting results from a network call). A good implementation will not block, but suspend execution, which will later resume.
In other words: 2 sequential function calls do not run concurrently, simply because they are called one after another. However, if you sequentially start new child coroutines (like Take explained very well), they have the possibility to run in parallel (if their context is multi threaded) or asynchronously, i.e. not synchronously with the scope that launched them.
j

Jimmy Alvarez

05/24/2021, 4:52 PM
WHen you said is supended while is waiting a remote call response seem similar to what we can see in launching Futures in java.
Like, the call is in progress
View count: 3