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

    Shawn Witte

    10/05/2020, 7:42 AM
    Is there an explanation somewhere for the
    native-mt-#
    coroutine releases? Dependabot keeps recommending these after the standard releases.
    t
    • 2
    • 2
  • n

    neworldlt

    10/05/2020, 9:11 AM
    What is the best practice of rethrowing CancellationException if I am catching all exceptions? Do I need to rethrow CancellationException at all?
    val foo = runCatching { bar() }.getOrNull()  // or similar try-catch block
    g
    s
    a
    • 4
    • 15
  • x

    Xitij

    10/05/2020, 9:14 AM
    suspend fun jobLifecycle () = coroutineScope {
       val job =  launch{
           println("Working....")
           delay(2000L)
           println("Done !")
        }
    
        delay(1000L)
        job.cancel() 
        // delay(1L) i have to do it to print correct value of job.isCompleted below
    
        println("isCompleted: ${job.isCompleted}") // it is printing "false" but if i delay for some time after cancelling the job it prints  "true".
    
    }
    is it my computer or it really takes some time to move job from cancelling to cancelled state where isCompleted becomes true after cancellation of job or is there something i'm missing out please review🔦
    t
    j
    • 3
    • 3
  • d

    Daniele Segato

    10/05/2020, 11:00 AM
    @travis I believe you are the author of this comment? https://github.com/Kotlin/kotlinx.coroutines/pull/2069#issuecomment-702523785 Running into unexpected behavior when trying out 
    MutableSharedFlow
    . Apologies, as this is a very simplified example from a larger codebase and hopefully it isn't merely demonstrating a gross misuse of 
    SharedFlow
     and 
    onSubscription
    .
    private val counter = AtomicInteger()
    
    class Example {
    
        private val scope = CoroutineScope(Job())
    
        private val _incoming = MutableSharedFlow<Int>(replay = 0)
        private val incoming: SharedFlow<String> = _incoming
            .onSubscription { emit(-1) }
            .map {
                // Emulate expensive operator that we want to "share".
                delay(500L)
                it.toString()
            }
            .shareIn(scope, replay = 0)
    
        suspend fun request(): String =
            incoming
                .onSubscription { _incoming.emit(counter.incrementAndGet()) }
                .first()
    }
    
    fun main() {
        val example = Example()
        repeat(10) {
            val result = runBlocking { example.request() }
            println(result)
        }
    }
    Output:
    -1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    1
     was expected after 
    -1
     but is missing.
    t
    • 2
    • 7
  • d

    Davide Giuseppe Farella

    10/06/2020, 9:37 AM
    Hello guys, given a function like
    suspend fun getThree() = 
      withContext(IO) {
        val one = async { getOne() }
        val two = async { getTwo() }
        
        one.await() + two.await()
      }
    would be better to be wrapper in a
    coroutineScope
    or would the
    withContext
    be enough?
    o
    g
    • 3
    • 7
  • a

    ahulyk

    10/06/2020, 1:02 PM
    Nice to have a book to read about Coroutines (something like Kotlin in Action). Maybe someone has any info about that?
    d
    c
    • 3
    • 2
  • j

    jaqxues

    10/06/2020, 7:17 PM
    I currently have a listener pattern that just puts functions in a list and invokes them if a new event occurs can i make this pattern use flows instead? the problems i imagine: * can multiple collectors get the same values? * can i "unsubscribe" collectors? I currently have a channel, so i can dispatch events from somewhere else, flow just did not fit my needs. So channel.receiveAsFlow is what i would want, but that would make it so I can only collect the element once.
    a
    • 2
    • 3
  • k

    Kush Patel

    10/07/2020, 12:40 AM
    👋, I am trying to convert a threaded worker loop to coroutine worker loop.
    val workers = ArrayList<Future<*>>(10)
    try {
        for (i in 1..10) {
            val task = getTask() ?: break
            workers += taskExecutor.submit {
                workerLoop(task) // some computation
            }
        }
    } catch (t: Throwable) {
        // log error
    }
    
    workers.forEach {
        try {
            it.get()
        } catch (t: Throwable) {
            // log error
        }
    }
    Proposed coroutine worker
    val workers = ArrayList<Deferred<*>>(10)
    try {
        for (i in 1..10) {
            val task = getTask() ?: break
            workers += taskExecutor.async {
                workerLoop(task) // some computation
            }
        }
    } catch (t: Throwable) {
        // Log error
    }
    
    runBlocking {
        workers.forEach {
            try {
                it.await()
            } catch (t: Throwable) {
                // Log error
            }
        }
    }
    Is this the right way to switch from threads to coroutines?
    g
    • 2
    • 10
  • p

    Pablo

    10/07/2020, 9:33 AM
    I have already ask this here but is still causing me overhead, if on my test presenter I'm creating a val dispatcher = TestCoroutineDispatcher() and a TestCoroutineScope(dispatcher) is there any difference if I do this? And I create the presenter as : presenter=MyPresenter(..,testscope,testdispatcher) runBlockingTest{ Here my presenter creates a launch{} } dispatcherTest.runBlockingTest{ Here my presenter creates a launch{} } scopeTest.runBlockingTest{ Here my presenter creates a launch{} } I've read the documentation and inside of the runBlockingTest is creating a TestCoroutineScope() but then it's not aligned or it's not the same as the presenter? So if the presenter takes longer or fails what will happen? This api creates a TestCoroutineScope() to act as a parent of the one is in the block? Because the thing is that I want the presenter (the dispatcher or scope) to avoid fails on the CI because maybe on my local machine passes but in a slow machine it doesn't wait until the end and fails. Any idea?
    g
    • 2
    • 11
  • s

    Se7eN

    10/07/2020, 9:50 AM
    So I'm trynna replace my LiveData with a StateFlow. I want to trigger an update whenever it's first accessed. I was using
    liveData
    builder before like this:
    val users = liveData {
        emit(getUsers(count=20))
    }
    With StateFlow, I'm doing it with `lazy`:
    val users by lazy {
        MutableStateFlow<List<User>>(listOf()).also { usersFlow ->
            viewModelScope.launch {
                usersFlow.value = getUsers(count = 20)
            }
        }
    }
    Just wanna know if it's fine to do it this way?
    e
    • 2
    • 10
  • e

    Erik

    10/07/2020, 10:42 AM
    I'd like more insights in my coroutine stacktraces of production crashes on Android. I use Firebase Crashlytics) and I came across: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-debug/ On Android it seems hard to make this work. I added the coroutines-debug dependency, the aspectj-gradle-android plugin and in my application
    onCreate
    I call
    DebugProbes.install()
    . Running the app leads to an immediate crash about
    java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/R$string
    . 😞 (Note that I don't even need to call
    DebugProbes.install()
    , so the issue lies elsewhere). Has anybody got experience with debugging Android coroutine stacktraces in production, or any other tips on how to do this?
    g
    • 2
    • 10
  • p

    Pablo

    10/07/2020, 2:06 PM
    Is it necessary to call scope.cancel in the onDestroy() without using job? For instance, one method that is using launch{} without assign it to a job? I guess is for avoid leaks, right? If I'm injecting mainScope() and a Dispatcher is necessary that on onDestroy cancel both?
    s
    • 2
    • 8
  • o

    obobo

    10/07/2020, 7:47 PM
    if i create a
    CoroutineScope
    with a
    SupervisorJob()
    and
    launch
    off it, will CoroutineScopes created from its
    coroutineContext
    inherit the SupervisorJob properties? if that second scope launches its own coroutines, will they inherit?
    l
    • 2
    • 1
  • a

    agu

    10/07/2020, 8:45 PM
    Hi I'm wondering what are the benefits of using
    <http://Dispatchers.IO|Dispatchers.IO>
    instead of creating a custom
    Executor.asCoroutineDispatcher
    , supposing that I'm executing IO operations (http calls)
    z
    r
    • 3
    • 3
  • j

    Jan Skrasek

    10/08/2020, 8:15 AM
    Let's have a flow collection. Something like
    interface Foo {
        suspend fun test(i: Int)
      }
    
      @Test
      fun myTest() = testCoroutineDispatcher.runBlockingTest {
        val mutableState: MutableStateFlow<Int> = MutableStateFlow(1)
    
        val foo = mockk<Foo>()
    
        val job = launch {
          mutableState
            .filter { it != 1 }
            .collect {
              delay(100)
              foo.test(it)
            }
        }
    
        mutableState.value = 2
    
        // how to wait here to be able to verify?
    
        coVerify {
          foo.test(2)
        }
      }
    How to wait for the flow collection? Some part of the flow runs immediately and ultimately the execution is switched back to the test and assertion fails since the collection haven't run yet.
    b
    • 2
    • 5
  • a

    Ahmed Ibrahim

    10/08/2020, 1:10 PM
    I'm using Room Database along with their coroutines support for managing the DB in my app, and I'm doing lots of queries in transaction since they span multiple relationships. I noticed that they use a thread pool of 4 threads to execute queries there, however this causes some long loading times due to queries being queued until one of the 4 threads is free to continue executions. I thought about customizing the Query executor by providing
    <http://Dispatchers.IO|Dispatchers.IO>.asExecutor()
    , but I'm wondering if that would be an appropriate solution since as far as I learned
    Dispatchers.Default
    shares some threads from IO and that might cause another set of problems. So the question is, would that be a good solution to the problem from multi-threading perspective?
    g
    b
    • 3
    • 7
  • s

    sandjelkovic

    10/08/2020, 1:38 PM
    Hi all, are there any books on Coroutines, that go a bit deeper and into more advanced topics that just standard usage?
    👀 1
    j
    g
    a
    • 4
    • 5
  • u

    uli

    10/08/2020, 2:54 PM
    Hi all, is it true that the 1.4 debugger features for debugging coroutines is JVM only. i.e. no android support?
    r
    • 2
    • 2
  • m

    Marc Knaup

    10/08/2020, 10:06 PM
    Has anybody written something like a concurrent FIFO processing queue with a dynamic concurrency limit? I want to process operations in parallel but the desired concurrency changes over time. Example: I throw 50,000 elements at once into the queue. The concurrency starts with 100, so up to 100 elements will be processed in parallel at any given time. After a while the error count increases, so I want to dynamically reduce the concurrency to 20. The number of elements processed in parallel will go down from 100 to 20 as the processing for more elements completes. Once the error count is back to zero for a little while, I change the concurrency to 100 again. Now there will be a sudden jump from 20 elements processed in parallel back to 100. The sender that puts something in the queue should be blocked and the result returned or an exception be thrown.
    z
    d
    s
    • 4
    • 13
  • c

    CLOVIS

    10/09/2020, 5:14 PM
    I'm working on a project where the main thread should never block or even be slowed down. To ensure that any ‘expensive' calculation (everything taking ~10ms or more is too much) is never executed on the main thread, I'm thinking to add the
    suspend
    modifier to anything that might be expensive, even if it doesn't suspend, to ensure I don't accidentally call it on the main thread. Do you think it's a good/bad idea? Are there any performance implications of the added parameter? It's a JVM-only project, and I don't care about Java interoperability here.
    l
    l
    • 3
    • 7
  • w

    william

    10/10/2020, 4:58 PM
    i'm a little confused as to why channel operators have been deprecated - if i need a stream to remain hot (using a channel), i can't use Flow and its operators
    a
    g
    • 3
    • 5
  • m

    Marc Knaup

    10/10/2020, 6:58 PM
    Is using
    AtomicRef
    and
    Deferred
    a good approach to ensure that concurrent calls to
    update()
    never cause more than one
    updateAsync()
    execution in parallel? For example let’s say
    updateAsync()
    execution takes 10 seconds and there are 4 calls to
    update()
    with 2 seconds in between.
    updateAsync()
    would only be called once and they all share the same result, right?
    d
    c
    • 3
    • 15
  • g

    Gilles Barbier

    10/11/2020, 8:16 AM
    Hi all, if I have n workers listening the same channel, does Kotlin provide a way to distribute messages to a specific worker according to a key? (equivalent of "key shared" feature of some queueing systems... https://pulsar.apache.org/docs/en/2.6.1/concepts-messaging/#key_shared) ?
    a
    • 2
    • 6
  • m

    Marc Knaup

    10/11/2020, 1:20 PM
    Is there a quick & dirty version of the
    shareIn
    Flow operator with
    WhileSubscribed
    behavior? I’d like to roughly have that behavior already and swap with
    shareIn
    later on. I have plenty of duplicate executions upstream where I’d like results to be shared.
    l
    • 2
    • 3
  • s

    Saiedmomen

    10/11/2020, 8:59 PM
    There is mention of data flow in state flow doc here. I suspect it is remains of an older name.
    All methods of data flow are **thread-safe** and can be safely invoked from concurrent coroutines without
    external synchronization.
    I wanted to open an issue but wasn't 100% sure so I thought better check it here first and avoid potentially clogging the repos issues
    g
    • 2
    • 2
  • m

    Marc Knaup

    10/11/2020, 9:06 PM
    Is there a performant way to transform
    List<Flow<T>>
    into
    Flow<List<T>>
    where
    List<T>
    contains the latest value of each
    Flow<T>
    at the same index.
    combine()
    is not an option.
    m
    b
    • 3
    • 10
  • t

    thana

    10/12/2020, 6:15 AM
    Hi, are there any guarantees regarding the thread an
    actor
    is run within?
    g
    • 2
    • 12
  • r

    ribesg

    10/12/2020, 12:37 PM
    Would you use
    isActive
    instead of
    true
    as an infinite
    while
    loop condition in a coroutine if the loop calls suspending functions (
    delay
    , among others)? I don’t think it changes anything, but maybe it makes things more clear to the reader? Thoughts?
    l
    • 2
    • 4
  • m

    Milan Hruban

    10/12/2020, 4:17 PM
    Hi, can someone please explain why following takes 5000ms instead of 200ms? And how do I make the
    withContext
    call cancellable by timeout?
    fun main() = runBlocking<Unit> {
        withTimeout(200) {
            withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                Thread.sleep(5000)
            }
        }
    }
    z
    i
    +3
    • 6
    • 7
  • m

    Marcelo Hernandez

    10/12/2020, 9:00 PM
    Hello. Just wanted to warn anyone who is integrating Coroutines/Flow into an existing RxJava-based code base that
    ObservableSource.asFlow()
    has proven, at least for me, to be quite unsafe and can even crash your app. I have several stack traces in https://github.com/Kotlin/kotlinx.coroutines/issues/2104.
    👍 1
    w
    • 2
    • 6
Powered by Linen
Title
m

Marcelo Hernandez

10/12/2020, 9:00 PM
Hello. Just wanted to warn anyone who is integrating Coroutines/Flow into an existing RxJava-based code base that
ObservableSource.asFlow()
has proven, at least for me, to be quite unsafe and can even crash your app. I have several stack traces in https://github.com/Kotlin/kotlinx.coroutines/issues/2104.
👍 1
It seems that using this extension within streams that leverage
combine
or
flatMapLatest
, or any operators that cause downstream cancellations where
ObservableSource.asFlow()
is used in the downstream may run into race conditions where the Coroutine might get cancelled concurrently while the Rx
Observable
is still emitting, causing a
JobCancellationException
or a
ChildCancelledException
.
I wish I had a solid and consistent repro, but unfortunately that is currently not the case. 😞
w

wbertan

10/13/2020, 8:08 AM
I got what I think similar case with Rx 😞 In my case I did
dispose
which then something finished and throw exception and I got
io.reactivex.exceptions.UndeliverableException
(The code contains a proper error handler - where usually was the reason for this error) So I found this issue in GitHub: https://github.com/ReactiveX/RxJava/issues/4991 with this comment:
This is by design, your Callable crashes and the downstream has disposed so the operator routes the error to the global error handler as it can’t know if the exception is relevant or not. Don’t crash into RxJava and consider using create() with emitter.tryOnError() instead.
The problem in my case the “Callable crash” was in Retrofit as the exception is:
Caused by retrofit2.adapter.rxjava2.HttpException
HTTP 404 Client Error
So not sure if in my case I would be able to handle better as the comment suggests with
create()
and `emitter.tryOnError()`… Anyway, it was the first time we notice this kind of Exception like this, and it was in our Alpha build (internal), so we will keep an eye and if becomes more often we will act on it.
m

Marcelo Hernandez

10/23/2020, 7:17 PM
Interesting scenario. 🤔
The
ObservableSource.asFlow()
crasher has been fixed and will be included in the Coroutines 1.4 release 🎉 https://github.com/Kotlin/kotlinx.coroutines/pull/2333 Thanks @louiscad, @Tash, and @Vsevolod Tolstopyatov [JB] 👏
🙂 1
View count: 9