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
  • o

    okarm

    09/01/2020, 3:28 PM
    Maybe not related to coroutines, but that's where I found it: Can anybody explain to me why the following code works? https://pl.kotl.in/O8wu8VKSE In essence the code sets an instance of type
    B
    as a value of
    StateFlow<A>
    . I would not expect that to be possible. The code not only compiles, it actually runs in the Playground without a run-time exception.
    o
    w
    a
    • 4
    • 15
  • s

    Slackbot

    09/02/2020, 5:45 AM
    This message was deleted.
    o
    m
    • 3
    • 3
  • g

    genovich

    09/02/2020, 9:01 AM
    Hi, I want to define list of operations that will be executed later. What is better solution in this case? •
    List<Deffered<T>>
    •
    List<suspend () -> T>
    👍 2
    o
    • 2
    • 10
  • g

    genovich

    09/02/2020, 11:25 AM
    Is there some way to get job from
    CoroutineContext
    by key and cancel it?
    s
    e
    • 3
    • 13
  • d

    Daniele Segato

    09/03/2020, 9:23 AM
    I'm migrating libraries from Rx to Kotlin Coroutines/Flow --- would be nice if I could start using
    shareIn
    /
    stateIn
    operators... I'm currently planning to work around those by transforming to Rx, using
    publish().refCount()
    or
    replay().refCount()
    and then turning it back to
    Flow
    cause i can't wait anymore for the new operator. I need to stabilize the API so the only other option without those operators is to go with Rx. When
    shareIn
    will be available I should be able to remove the Rx dependency without having to modify the API interface (hopefully). Do you know if there's something particular holding back the release of
    ShareFlow
    or if we could expect it to be available soon?
    ➕ 1
    • 1
    • 1
  • a

    Andrea Giuliano

    09/03/2020, 2:38 PM
    Hi guys, I have some libraries that use ThreadLocal in my application and I’m using the
    .asContextElement()
    extension function to make them coroutine-ready. All works well but i find my code having something like this
    launch(object1.asContextElement() + object2.asContextElement()) {}
    I was thinking to encapsulate those element into a container such that I can do something like this
    launch(myContext) {}
    where
    mycontext
    contains the elements from object1 and object2. I was thinking to do this by implementing the
    CoroutineContext
    interface but I then I need to implement all its functions, while what I really want is just the default
    +
    behavior. Is there any nice way to achieve this?
    e
    • 2
    • 8
  • d

    Dougie

    09/04/2020, 3:32 AM
    hey guys, there is a flow return a list that every item with a retrofit api service, then i want to get all detail from remote api in one time, not like
    flatMapConcat
    one by one.
    flatMapMerge
    can not do it, and start coroutines will break the flow are there any good solutions? thanks
    d
    • 2
    • 1
  • m

    Maurice Jouvet

    09/04/2020, 2:35 PM
    I have a question, it's clearly my misunderstanding, but, I have a JobCancellation on my Workers ($doWork: kotlinx.coroutines.JobCancellationException: Job was cancelled;) Only when my screen is off. If the app is the background or if we are on the app. No problems.
    i
    • 2
    • 5
  • a

    ansman

    09/04/2020, 5:14 PM
    Hmm, why is
    Flow.firstOrNull
    restricted to non nullable types? Feels like it'd be useful even with flows with nullable types?
    c
    l
    • 3
    • 13
  • b

    bezrukov

    09/06/2020, 5:30 PM
    hi everyone, why if I convert flow to a rendezvous channel (I need it for custom operator) and collect it, unnecessary dispatch (between collecting 1 and 2.) is performed. Is there a way to fix this?
    val flow = flowOf(1, 2)
    produce(capacity = 0) { flow.collect { send(it) } }.consumeAsFlow()
       .onEach { println("each $it") }
       .launchIn(this)
    I would expect there will be no difference comparing with:
    val flow = flowOf(1, 2)
    flow.onEach { println("each $it") }
       .launchIn(this)
    Link demonstrates unnecessary redispatch: https://pl.kotl.in/LbbXNwWzU
    g
    • 2
    • 1
  • r

    Robert von Massow

    09/07/2020, 9:34 AM
    so we’re experiencing some problems with flows and coroutines. general setup: we have a grpc stream that provides messages as flow. inside the collect we launch a new coroutine to do some heavy lifting. this is of course done in a different coroutine context (using the default dispatcher, we used a custom dispatcher before and had the same problem so we went back to the default). what we see now is that after some time, the inner launch is just not scheduled/executed, it’s not blocking, though, the launch actually returns and thus the flow is also consumed properly. we struggle hard reproducing or even just monitoring this issue. here is somewhat example code (our input arrives a lot slower, though). we at some point still see logs like “received” but no “processing” anymore. probably we are doing something really wrong, has anyone seen this before?
    runBlocking {
        val coroutineScope = CoroutineScope(EmptyCoroutineContext)
        val flowScope = CoroutineScope(EmptyCoroutineContext)
        flowScope.launch {
            val flow = flowOf(1)
            while (isActive)
                flow.collect { i ->
                    println("received $i")
                    coroutineScope.launch {
                        // Offload some hard work
                        println("processing $i")
                        Thread.sleep(1000)
                        println("done processing $i")
                    }
                }
        }
    
        // just added so it doesn't terminate right away
        delay(10000)
    }
    z
    • 2
    • 6
  • g

    Glen

    09/07/2020, 10:27 AM
    Everything is labeled out here : https://github.com/AnonymousGeekDev/FastLightJP2/blob/coroutine-optimized/app/src/main/java/com/example/jp2ssr/kotlin/MainActivity.kt
    t
    w
    b
    • 4
    • 29
  • r

    rrva

    09/07/2020, 10:47 AM
    I have a wrapper function to limit concurrent calls to a service looking like this:
    private val concurrentRequests = Semaphore(50)
    
    private suspend fun <T> requestWithLimit(block: suspend () -> T): T {
        try {
            withTimeout(10) {
                concurrentRequests.acquire()
            }
        } catch (e: Exception) {
            throw RuntimeException("Overloaded", e)
        }
        try {
            return block()
        } finally {
            concurrentRequests.release()
        }
    }
    I usually call io.ktor.client.HttpClient.request inside block(). If I want to write it as an extension function on io.ktor.client.HttpClient (just to make the call site a bit cleaner), how would I define it? It seems that the extension function cannot access the variable
    concurrentRequests
    w
    • 2
    • 2
  • a

    Ale

    09/07/2020, 11:29 AM
    I'm using callbackFlow to adapt a callback from Firestore into a flow, and then store the received data locally, as a "fire and forget" call. I can do this:
    @ExperimentalCoroutinesApi
    private fun retrieveFromFirestore(porteroId: String): Flow<Portero> = callbackFlow {
        val porteroCallback = EventListener<QuerySnapshot> { querySnapshot, e ->
            val element = //extract data from snapshot etc.
                 launch { //save to local sqllite }
            offer(element)
        }
    }
    This works well. However, when I tried to refactor the code a bit, and extract the snapshot manipulation to another method:
    @ExperimentalCoroutinesApi
    private fun retrieveFromFirestore(porteroId: String): Flow<Portero> = callbackFlow {
        val porteroCallback = EventListener<QuerySnapshot> { querySnapshot, e ->
            val element = buildData(querySnapshot, e)
            offer(element)
        }
    }
    
    private buildData(querySnapshot: QuerySnapshot?, e: FirebaseFirestoreException?): Element {
        //extract data from snapshot etc.
        launch { //save to local sqllite }  // <--- this doesn't compiles
        return element
    }
    The launch function is no longer available, with the error Unresolved reference. I can fix it using
    CoroutineScope(Dispatchers.Default).launch { ... }
    but why is this happening? How come launch is available only in the calling function but not in the called one?
    m
    w
    • 3
    • 3
  • h

    Hakob Vardanyan

    09/07/2020, 2:39 PM
    Hello ladies and gentlemen. Who knows when
    flowOn, launchIn, etc
    functions will be released?
    b
    • 2
    • 4
  • g

    George Theocharis

    09/07/2020, 3:31 PM
    Hello all 👋 Is there a channel that emits its value to all subscribers, while suspending (keeping the value) if none is subscribed and then the value gets consumed?
    p
    w
    g
    • 4
    • 11
  • m

    MiSikora

    09/07/2020, 7:37 PM
    Is it expected that
    kotlin.Result.Failure
    throws instead of delivering value when continuation is resumed on a different thread?
    suspend fun main() {
        val failure = fail()
        println(failure)
    }
    
    suspend fun fail() = suspendCoroutine<Result<String>> {
        Executors.newSingleThreadExecutor().execute {
            it.resume(Result.failure(RuntimeException()))
        }
    }
    Exception in thread "main" java.lang.RuntimeException
    	at MainKt$fail$2$1.run(main.kt:12)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    	at java.lang.Thread.run(Thread.java:748)
    g
    • 2
    • 7
  • g

    gotoOla

    09/07/2020, 10:16 PM
    what is the meaning of "(Coroutine Boundary)" if you see them in a stacktrace?
    g
    • 2
    • 1
  • f

    Fernando Branbila Cunha Junior

    09/08/2020, 12:45 AM
    I'm very new to Kotlin and so, to co-routines. I'm trying the following snippet, but the program always finishes before printing "data". Could'nt make progress out of it
    fun main() {
        GlobalScope.launch {
            val deferredUser = getUserByIdAsync(1)
            val data = deferredUser.await()
            print(data)
        }
    }
    
    
    private suspend fun getUserByIdAsync(userId: Int) =
            GlobalScope.async {
                println("Retrieving user from network")
                delay(3000)
                println("Still on coroutine")
                User(userId, "John", "Silva")
            }
    a
    j
    • 3
    • 5
  • e

    Erik

    09/08/2020, 1:30 PM
    With flows it's simple to
    debounce
    input. I'd like to know if some value is currently being debounced (and I'd like to know the value), so that I don't have to wait for it to be collected downstream. How would I do that?
    s
    d
    • 3
    • 8
  • j

    Joe

    09/08/2020, 10:47 PM
    I have a
    suspend
    method that gets dynamically overridden by Guice AOP. It appears that if I have a method handle and use
    method.kotlinFunction.callSuspend(obj, *args)
    to call that method, it fails because the wrapped method's
    isSuspend
    property is false (probably because it's dynamically generated by something that is not the kotlin compiler and doesn't know about suspend functions). It looks like I can use
    suspendCoroutineUninterceptedOrReturn { method.kotlinFunction.call(obj, *args, it)}
    to bypass the
    isSuspend
    check, but is that safe or is there another approach I should take?
    e
    • 2
    • 2
  • m

    Mijael Viricochea

    09/09/2020, 2:21 PM
    Hi everyone, I'm trying to use MutableStateFlow, encapsulating a List of an object, but when I update it with some new value, the collectLatest{} method doesn't work, can you help me please? This method doesn't update the value
    @ExperimentalCoroutinesApi
    fun deleteSelected() {
        val value = dataPoints.value
        value.removeAll { it.selected }
        dataPoints.value = ArrayList(value)
    }
    b
    • 2
    • 8
  • d

    dan.the.man

    09/09/2020, 2:31 PM
    I seem to have an incorrect understanding and I was wondering if someone could help.
    Fragment {
      lifecycleScope.launch { vm.attachListeners }
    }
    
    VM {
      val locationListener:ReceiveChannel<Location>
      val navListener:ReceiveChannel<NavEvent>
    
      suspend fun attachListeners(){
         locationListener.consumeEach{//Do stuff}
         navListener.consumeEach{//do stuff}
      }
    With the code above, if this was RxJava, it would behave correctly. With Coroutines the first
    .consumeEach
    is blocking it appears, never executing the second one. I can change it to
    suspend fun attachListeners(){
        coroutineScope{
         launch{
           locationListener.consumeEach{//Do stuff}
         }
         launch {
           navListener.consumeEach{//do stuff}
         }
      }
    }
    And that will work. The goal is to make it automatically cancel with the lifecycleScope, I'm wondering is there a better way of doing this? And why does .consumeEach block?
    c
    b
    • 3
    • 9
  • r

    Rechee Jozil

    09/10/2020, 5:03 AM
    why hasn't coroutines-test runBlockingTest been fixed yet...
    s
    l
    w
    • 4
    • 8
  • f

    flosch

    09/10/2020, 5:36 AM
    I want to create a library with a custom time-based operator extension on Flow, such as for example
    Flow<T>.throttleFirst()
    here. @elizarov wrote that to test such an operator we would have to use the
    DelayController
    if available instead of
    System.currentTimeMills()
    , which of course makes total sense. My question: How could I publish this library without having
    kotlinx-coroutines-test
    in the release dependencies? Meaning how would I prevent the user of my library having
    kotlinx-coroutines-test
    in their release binaries when they use my dependency?
    l
    • 2
    • 7
  • k

    KayCee

    09/10/2020, 8:45 AM
    What would be like in coroutines in case I want to do one job first -> wait that to finish -> then 2 other jobs later?
    g
    j
    r
    • 4
    • 6
  • b

    bsimmons

    09/10/2020, 12:57 PM
    Multiplatform question. I am trying to get
    delay {}
    and
    runBlocking {}
    working on iOS/native. Currently, I am trying out
    <http://1.3.5-native.mt|1.3.5-native.mt>
    and am getting some bizarre/arbitrary freezing errors that would otherwise work on the JVM. What is the recommended way of launching coroutines on iOS? Is there a guide or template anywhere? Is it worth upgrading to 1.4 and using the latest version?
    t
    • 2
    • 2
  • f

    Fernando Branbila Cunha Junior

    09/10/2020, 1:05 PM
    How can i properly pass the value of a async function so i can use "outside" it? I need to do 1 for each block like:
    val bar = async { foo() }
    Or there's a way to do like:
    async { val bar = foo() }
    and then use bar value?
    g
    s
    u
    • 4
    • 15
  • e

    Erik

    09/10/2020, 5:41 PM
    The other day I came across
    suspend fun main()
    for the first time. Where is it documented? How does it work?
    w
    z
    g
    • 4
    • 9
  • z

    zak.taccardi

    09/10/2020, 8:05 PM
    Given a
    CoroutineScope
    , what is the idiomatic way to create a child scope?
    w
    c
    +2
    • 5
    • 18
Powered by Linen
Title
z

zak.taccardi

09/10/2020, 8:05 PM
Given a
CoroutineScope
, what is the idiomatic way to create a child scope?
w

wasyl

09/10/2020, 8:06 PM
I suppose it’s
coroutineScope { }
z

zak.taccardi

09/10/2020, 8:08 PM
I’m not in a suspending content
I would need to implement:
(CoroutineScope) -> CoroutineScope
where the output is a child scope
maybe a better question is a child job
This is just a terrible API lol
val globalSdkScope: CoroutineScope

val childScope = globalSdkScope + Job(globalSdkScope.coroutineContext[Job]!!)
➕ 2
c

Casey Brooks

09/10/2020, 8:18 PM
I think you’re looking for a SupervisorScope rather than a normal CoroutineScope
z

zak.taccardi

09/10/2020, 8:18 PM
why? I would want a failure with the child to fail the parent
cancelling a child won’t cancel the parent right?
c

Casey Brooks

09/10/2020, 8:21 PM
Yeah you’re right. But it also sounds weird to have a “global” context cancelled when a child does (from your snippet)
z

zak.taccardi

09/10/2020, 8:21 PM
when a child does what?
the parent would only fail if the child fails
if the child is cancelled normally then the parent would still be active
z

Zach Klippenstein (he/him) [MOD]

09/10/2020, 8:45 PM
The API is very bad, I agree. I filed an issue about this a year ago, if you wanna 👍: https://github.com/Kotlin/kotlinx.coroutines/issues/1485
z

zak.taccardi

09/10/2020, 8:46 PM
already did! haha
I’m using these two functions as a workaround for now
public fun CoroutineScope.newChildScope(
    context: CoroutineContext = EmptyCoroutineContext
): CoroutineScope {
    val parentScope = this

    return parentScope + parentScope.job.newChildJob() + context
}

public fun Job.newChildJob(): Job {
    val parentJob = this

    return Job(parent = parentJob)
}
g

gildor

09/10/2020, 11:53 PM
Just curious, what is your use case for this? I think it doesn't have any helper functions because it low level staff which useful for library authors rather than for end users For example your snippet will crash when you try to get Job from GlobalScope, so it's up to you decide how this function should behave in this case
z

zak.taccardi

10/06/2020, 10:18 PM
GlobalScope
should never be used, though
g

gildor

10/06/2020, 11:35 PM
It's an overstatement
View count: 3