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

    prasham.h.trivedi

    01/10/2019, 7:17 AM
    Is there any possibility that
    withTimeOut
    construct doesn’t throw
    TimeOutCancellationException
    ? In my android service I am using combination of timeout + channels to send data to specified duration using channels, and the sending operation should end after specified time. I have observed that channels kept sending the data well past timeout limit. Here is my pseudocode
    launch(<http://Dispatchers.IO|Dispatchers.IO>) {
                        val openChannel = openChannel(interval = interval)
                        try {
                            withTimeout(timeMillis = duration) {
                                openChannel.consumeEach {
                                    doOnTick()
                                }
                            }
                        } catch (e: TimeoutCancellationException) {
                            openChannel.cancel()
                            stopService()
                        }
                    }
    In this code
    catch
    isn’t executed sometimes. This code runs properly on kotlin playground, what is wrong above?
    e
    d
    • 3
    • 5
  • s

    simon.vergauwen

    01/10/2019, 11:36 AM
    Can someone point me in the direction about some info about
    Unconfined
    &
    EmptyCoroutineContext
    ?
    v
    a
    • 3
    • 13
  • m

    matt tighe

    01/11/2019, 7:07 PM
    i’m having trouble with verification of suspending functions with mockito failing randomly. the tests most often pass, but will occasionally fail and i’m not sure why. for example:
    @Test
        fun `Submits app selection if selections can be made`() {
            mainActivityViewModel.submitAppSelection(selectedApp)
    
            runBlocking {
                verify(mockAppsStartupFsm).submitEvent(AppSelected(selectedApp))
            }
        }
    class MainActivityViewModel {
        fun submitAppSelection(app: App) {
            if (!selectionsCanBeMade()) return
            lastSelectedApp = app
    
            val coroutineScope = CoroutineScope(Dispatchers.Default)
            coroutineScope.launch { appsStartupFsm.submitEvent(AppSelected(app)) }
        }
    }
    AppsStartupFsm#submitEvent
    is a suspending function. Changing the runBlocking scope to be function level doesn’t seem to help. Is there something I’m missing with verification of suspending functions?
    g
    • 2
    • 27
  • g

    groostav

    01/11/2019, 10:04 PM
    yeah exactly @Allen Wang, the root problem is that this code doenst synchronize on the status of that
    submitEvent
    call
    a
    m
    • 3
    • 3
  • s

    Saiedmomen

    01/12/2019, 12:21 AM
    I'm getting this error while running junit test in android module
    Exception in thread "main" java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used
    Does anyone know
    Dispatchers.setMain
    with what parameter should be called?
    a
    • 2
    • 10
  • s

    Saiedmomen

    01/12/2019, 12:45 AM
    Unbenannt.kt
    a
    s
    • 3
    • 10
  • s

    Saiedmomen

    01/12/2019, 9:18 AM
    When I step through the code it fails on uiScope.launch {...} where uiScope is defined:
    -.kt
    d
    • 2
    • 6
  • z

    zjuhasz

    01/13/2019, 5:41 AM
    I found I was using actor a lot just to get concurrency safe access to some arbitrary mutable data but there’s a lot of boilerplate for even this very simple application of actor. So I made a general purpose actor for this and I was hoping someone could tell me if you see any obvious oversights in it. Like for example does passing the whole function to the actor as opposed to just some parameters cause significant performance degradation or something like that. Here is the code: https://gitlab.com/snippets/1797360
    d
    g
    g
    • 4
    • 17
  • h

    hmole

    01/13/2019, 2:09 PM
    How do I integrate OkHttp to work properly with
    ThreadLocal.asContextElement
    ? Currenlty I use retrofit with
    CompletableFuture
    futures and then using
    async
    extension function from jdr8 integration package. But the request itself is executed in OkHttp own thread pool and so my
    ThreadLocal
    is null there, since coroutine doesn't know about this thread.
    d
    g
    • 3
    • 11
  • g

    ghedeon

    01/13/2019, 7:24 PM
    [Android: LiveData —> Coroutines]. Probably you're aware of
    NetworkBoundResource
    from Google's app guide: https://developer.android.com/jetpack/docs/guide#addendum. How do you replicate similar functionality in coroutines world? Can you reuse it? Do you apply some completely different technic? Some thoughts: Case 1: network request, no caching required: Before: return
    LiveData<Resutl>()
    After: probably just
    suspended get(): Result
    ? Seems enough.
    Error/Success
    , no need for a stream here. Case 2: network request, return cache first, update cache, return fresh data Before: return
    NetworkBoundResource
    as LiveData (emits two items, cached and refreshed) After? Channels? Actors? (P.S. Does anybody have an example of cache aware Repository with coroutines? )
    d
    g
    r
    • 4
    • 6
  • a

    Allan Wang

    01/13/2019, 10:12 PM
    Is there a good way to offer events to channels but ignore it if the channel is closed? Currently it seems like only try catch would work, as checking for close beforehand isn't atomic.
    e
    • 2
    • 2
  • t

    thana

    01/14/2019, 7:46 AM
    in a blocking world it's easy to start the coroutine and either sleep for an amount of time or wo wait on a latch or something. but these approaches wont work with js...
    g
    • 2
    • 4
  • m

    marcinmoskala

    01/14/2019, 8:14 AM
    I am preparing Kotlin Coroutines Cheatsheet. Any suggestions? Something to change/correct?
    👍 11
    l
    e
    +6
    • 9
    • 25
  • a

    Alexjok

    01/14/2019, 8:32 AM
    Hello, can anyone explain channels are thread safe structure? When is a global variable
    g
    • 2
    • 2
  • d

    dave08

    01/14/2019, 4:19 PM
    Looks like just closing the actor wasn't enough, but when I cancel the
    coroutineScope { }
    that contains it, it works... why should it work that way?
    g
    d
    • 3
    • 3
  • m

    maxmello

    01/14/2019, 4:25 PM
    Let’s assume if have a function which has some part that has to be done on the main thread, and some calculations, but the whole function has to be blocking, not suspending. Is there any benefit from doing:
    fun doIt() = runBlocking { value = withContext(Dispatchers.Default) { // some calculations } }
    vs just doing everything on the main thread? As I understand,
    runBlocking
    will still block the main thread (if
    doIt
    is called from it), is there any practical difference between blocking the main thread by
    runBlocking
    and by just doing some calculations on the main thread?
    d
    g
    m
    • 4
    • 12
  • g

    ghedeon

    01/15/2019, 9:13 AM
    Must be something trivial. Why it's not getting caught?
    @Test
    	fun `Channel exception error handler`() {
    		val errorHandler = CoroutineExceptionHandler { _, throwable ->
    			assertThat(throwable.message).isEqualTo("Failure")
    		}
    		runBlocking(errorHandler) {
    			val channel = produce<Nothing> { close(Exception("Failure")) }
    			channel.consumeEach { println() }
    		}
    	}
    b
    e
    g
    • 4
    • 3
  • l

    leandrodev

    01/15/2019, 11:52 AM
    Is it possible to configure a project with kotlin coroutines/native with a gradle version different from
    4.7
    ? https://github.com/Kotlin/kotlinx.coroutines/tree/master/native My problem is that with the new android plugin version
    3.3.0
    requires at least a gradle version of
    4.10.1
    and it got complicated to update my mpp
    d
    d
    • 3
    • 3
  • m

    maxmello

    01/16/2019, 10:41 AM
    While migrating old code to coroutines I always encounter blocking code, like IO, synchronized blocks, wait / notify etc. Not everything can be changed to be suspending rather than blocking, so what is the worst case scenario with blocking code inside coroutines? Should I just always use the IO Dispatcher to make sure enough threads are available, or can blocking code inside coroutines have negative consequences to the point where I should explicitly not use them and stick to Thread? So for example, is
    GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) { synchronized(lock) { // some operations } }
    potentially worse than
    thread { synchronized(lock) { // some operations } }
    ?
    z
    d
    u
    • 4
    • 12
  • d

    Dalinar

    01/16/2019, 4:24 PM
    ah ok, I was thinking there might be major reworking of code needed..
    g
    g
    i
    • 4
    • 23
  • n

    nikospamp

    01/16/2019, 7:03 PM
    Hello guys, up until now I've been using rxjava for networking but now I'm trying to change to coroutines. On rx I have a central system that if a certain property on the network response has a certain value it maps it into a custom exception How can I do something like that on coroutines? https://stackoverflow.com/questions/54204547/central-error-handling-in-coroutines-kotlin
    g
    d
    • 3
    • 3
  • o

    octylFractal

    01/16/2019, 9:21 PM
    I'm trying to emulate `PipedInputStream`/`PipedOutputStream` with coroutines, does https://github.com/Kotlin/kotlinx-io provide anything like that? currently I have a
    ReceiveChannel<ByteReadPacket>
    but no way to turn that into an
    InputStream
    for a Java API. I don't care if the
    InputStream
    blocks instead of suspending, but I'd like keep it in coroutines until I hit Java
    • 1
    • 1
  • a

    Allan Wang

    01/17/2019, 6:58 AM
    I have the following block of code:
    scope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        val result = runCatching {
            fetcher(key)
        }
        receiverChannel.send(key to result)
    }
    The scope is currently
    GlobalScope
    and
    fetcher
    is a suspended function (that just returns an exception) Even with runcatching, I’m getting
    FATAL EXCEPTION: DefaultDispatcher-worker-4
        ...
        java.lang.RuntimeException: Test
    Is there something else I’m missing? Do I need to add a new scope here?
    o
    • 2
    • 5
  • g

    ghedeon

    01/17/2019, 10:03 AM
    How do you structure your API with channels? A common example from docs is
    fun CoroutineScope.foo(): ReceiveChannel<Int> = produce {}
    What if it's in a different class? Then the usage is ... strange? 🙂
    class Bar{
    fun CoroutineScope.foo(): ReceiveChannel<Int> = produce {}
    }
    
    .... coroutine scope ....
    bar().run {
       foo() ??
    }
    g
    s
    d
    • 4
    • 6
  • g

    ghedeon

    01/17/2019, 10:06 AM
    basically, I want my Repository to return channel and I thought
    produce
    is the way to go. Should I just pass
    CoroutineScope
    as a parameter?
    g
    • 2
    • 1
  • g

    ghedeon

    01/17/2019, 11:34 AM
    any
    ReceiveChannel.asLiveData()
    implementations?
    s
    a
    • 3
    • 3
  • d

    dave08

    01/17/2019, 2:57 PM
    Can't run a suspend function in a
    mapNotNull
    ...? It might be nice to add such extensions in kotlinx.coroutines that take suspend lambdas no (I don't know how this would work though)? Or use inline functions...
    w
    m
    e
    • 4
    • 15
  • a

    A Gamal

    01/17/2019, 4:45 PM
    I am a bit confused about
    TestCoroutineContext
    . In unit testing, should I init it in classes that have
    CoroutineContext
    in the constructor?
    s
    • 2
    • 4
  • h

    hohnjogan

    01/17/2019, 10:23 PM
    Messing around with coroutines for first time. Is there a better way to implement a timer that executes a block of code every x millis? I was hoping to avoid recreating the job every time but it seems that you cannot "pause" a coroutines and start it again. Thanks in advance.
    -.kt
    n
    g
    +3
    • 6
    • 5
  • m

    mingkangpan

    01/18/2019, 9:01 AM
    guys, I am confused
    coroutineScope(UI) {
            try {
                val a = async(IO) {
                    delay(1000)
                    println("Done after delay")
                }
                val b = async(IO) { throw Exception() }
                awaitAll(a, b)
            } catch (e: Exception) {
                println("Caught $e")
            }
        }
    ^ why does this crash my application? why is the exception not propagated to the outer
    try & catch
    ?
    ➕ 1
    g
    l
    • 3
    • 18
Powered by Linen
Title
m

mingkangpan

01/18/2019, 9:01 AM
guys, I am confused
coroutineScope(UI) {
        try {
            val a = async(IO) {
                delay(1000)
                println("Done after delay")
            }
            val b = async(IO) { throw Exception() }
            awaitAll(a, b)
        } catch (e: Exception) {
            println("Caught $e")
        }
    }
^ why does this crash my application? why is the exception not propagated to the outer
try & catch
?
➕ 1
g

gildor

01/18/2019, 9:02 AM
Because coroutineScope failed (because one of coroutines inside failed)
m

mingkangpan

01/18/2019, 9:03 AM
but why can't I just handle this in try and catch?
g

gildor

01/18/2019, 9:03 AM
this is required to avoid leaked coroutines
no, this is not that you cannot catch, try/catch also works
this is justt how coroutineScope works
if some coroutine inside failed, coroutineScope also fails
you need supervisorScope, if you want to manage it manually
see https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/exception-handling.md#supervision
m

mingkangpan

01/18/2019, 9:13 AM
okay wait, give me some time to read this, I just want to understand why this can't be a default behaviour like RX, if one of the child job fails, that the exception is propagated to the other try catch, it crashes application only if it is not handled
g

gildor

01/18/2019, 9:15 AM
Rx doesn’t have structured concurrency, so there is no direct analogy
it’s just a different level of exceptions. One handled inside of coroutine, another is thrown because child coroutine is crashed in coroutine scope, there is special param in Job that propagate exception to parent (which is false for SupervisorJob)
also, in general I don’t see why you need coroutineScope in this particular example
l

louiscad

01/18/2019, 11:08 AM
@mingkangpan Here's your code, fixed:
try {
    coroutineScope {
        val a = async(<http://Dispatchers.IO|Dispatchers.IO>) {
            delay(1000)
            println("Done after delay")
        }
        val b = async(<http://Dispatchers.IO|Dispatchers.IO>) {
            throw Exception()
        }
        awaitAll(a, b)
    }
} catch (e: Exception) {
    println("Caught $e")
}
m

mingkangpan

01/18/2019, 11:13 AM
thanks, if there any difference here?
scope(IO) {
   async { }
   async {  }
}
vs
scope {
   async(IO) { }
   async(IO) {  }
}
g

gildor

01/18/2019, 11:14 AM
No
I'm still not sure that you need coroutineScope, only if it's some standalone suspend function, but in this case just swallow exception is not good.
m

mingkangpan

01/18/2019, 11:54 AM
think that delay is in RL some IO request and exception if IO request fails I want both requests executed in parallel, the speed things up my main scope is Main thread to update the UI
g

gildor

01/20/2019, 11:38 AM
See, it's fine to use coroutineScope if you have some function that launches a few coroutines inside and return only when all of them are finished. I'm According to your use case it should be fine to use coroutineScope, just was not originally clear from your first example
View count: 3