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

    voben

    12/05/2019, 11:09 PM
    Trying to figure out how to test channels + flow but I keep running into a
    IllegalStateException: This job has not completed yet
    . I have a channel in my viewmodel which I expose as a flow ViewModel
    private val _channel = BroadcastChannel<Boolean>(1)
    val myFlow = _channel.asFlow()
    
    fun sendToChannel() {
        viewModelScope.launch {
            _channel.send(true)
        }
    }
    And in my activity, I collect the flow
    lifecycleScope.launch {
         myFlow.collect { println(it) }
    }
    My Test
    @Test
    fun `myTest`() = runBlockingTest {
        
        viewModel.myFlow.collect { myVal ->
            assertTrue(myVal)
        }
    
        viewModel.sendToChannel()
    }
    How do I ensure the assertion is called. Or what’s a better way of testing this?
    o
    s
    t
    • 4
    • 10
  • u

    ursus

    12/06/2019, 4:37 AM
    Is there much overhead (perf, memory, apk size) to have both rxjava & coroutines in app, given dispatchers are shared from rx schedulers? Is it reasonable?
    l
    • 2
    • 1
  • j

    jk2018

    12/06/2019, 5:45 PM
    Question about Workers on Kotlin/Native \ MP on windows: (I figured the coroutines channel was still the best place to ask the following, even tho I can't do this with coroutines (yet?).) I've checked out the workers example here [ https://github.com/JetBrains/kotlin-native/blob/master/samples/workers/src/workersMain/kotlin/Workers.kt ] and got that to work, but I am now wondering if there is a way ( in Kotlin, without resorting to sharing a buffer via C or something like that ) to have a long running process ( e.g. another windows program launched via popen ) running in a worker which periodically sends data ( e.g. a string of the output of the program ) back to the main thread. From what I understand, workers allow you to do work in a separate "environment", and then "transfer back" the (immutable) data once the worker is done. Is there a canonical way to periodically "send data back" to the "main thread"?
    g
    • 2
    • 9
  • a

    Animesh Sahu

    12/08/2019, 11:02 AM
    How do CoroutineScope() class works? what happens if you create multiple scopes on single context? and what's better
    CoroutineScope(context).async{}.await()
    or
    withContext(context) {}
    ?
    o
    d
    g
    • 4
    • 7
  • a

    Animesh Sahu

    12/08/2019, 11:11 AM
    Another quick question, what happens if you join two dispatchers? For example:
    Dispatchers.Default+<http://Dispatchers.IO|Dispatchers.IO>
    ? (I know its not intended i'm just curious of the functionality)
    o
    e
    • 3
    • 3
  • a

    asad.awadia

    12/08/2019, 3:49 PM
    Can a channel be easily converted to a flow?
    a
    • 2
    • 9
  • c

    Colton Idle

    12/09/2019, 8:00 AM
    Just learning coroutines (on Android in this example). I was expecting this to hang my app (ANR) because I didn't select a scheduler/dispatcher/thread/whateverItsCalledInKotlin
    fun buttonClick() {
        viewModelScope.launch {
            delay(10000)
            _myPrivateData.value = "Two"
        }
    }
    Is there an easy way to tell when a suspend function will run on a different thread? For example, I will be using coroutines with Retrofit and at first it seems like I would have to tell it to run on a different thread, but it seems like I won't have to do that from the tutorials I've read?
    o
    t
    +2
    • 5
    • 6
  • d

    Dmitry Khasanov

    12/09/2019, 11:51 AM
    Hi guys. What is the best way to implement some long running background work (like in attached code) using coroutines?
    Untitled
    d
    g
    b
    • 4
    • 16
  • n

    nerdstone

    12/09/2019, 2:25 PM
    Am experiencing some issue with writing coroutine test and I'm in need of help. So here is the situation, I have 2 different coroutine test classes that pass when I run them individually but when I run the entire tests in the package one passes wile the other fails.
    l
    l
    • 3
    • 8
  • g

    Gabriel Feo

    12/09/2019, 6:38 PM
    Hi! I need to run two `Job`s simultaneously, how would I do this with coroutines? I understand how to do this when I need return values with
    Deferred
    and
    awaitAll
    , but I don't know how I should do this with simple `Job`s
    l
    o
    +2
    • 5
    • 10
  • j

    jimn

    12/09/2019, 9:35 PM
    how does one simultaneously iterate on multiple flows in the same loop to get the same index? without calling toList() first
    e
    • 2
    • 14
  • d

    Daniel Asher

    12/10/2019, 5:37 AM
    Hi, I’m new to kotlin and coroutines, coming from RxFeedback on Swift/iOS and really excited about the language, platform and tooling. But I’m having some problems understanding exception handling. I’d like to have an event bus and state machine for a uniflow architecture and am used to wrapping this in a nice interface for clients. The reducer function throws an exception if the event in invalid and I’d like to give the client the option of handling this. It looks to me that I need a
    SupervisorJob
    and to
    launch
    a new coroutine for every transition so as not to have parent coroutines cancelled, but when I’m calling the API, I can’t quite figure out how to get the exception back to the client. Here’s some code, apologies for any conceptual errors on my part:
    class CoroutineExceptionTest: BehaviorSpec() {
    
        val supervisorJob = SupervisorJob()
        val coroutineScope: CoroutineScope = CoroutineScope(newSingleThreadContext("serviceContext") + supervisorJob)
        class InvalidEventException(override val message: String): Exception(message)
        fun tryTransition(state: Int, event: Int): Int {
            return when (event >= state) {
                true -> event + state
                false -> throw InvalidEventException("Argument $event is invalid")
            }
        }
        val stateChannel = ConflatedBroadcastChannel(0)
        val currentState: Int get() = stateChannel.value
    
        var eventChannel = coroutineScope.actor<Int>() {
            for (event in channel) {
                if (coroutineScope.isActive) {
                    launch {
                        val newState = tryTransition(currentState, event)
                        stateChannel.send(newState)
                    }
                }
            }
        }
    
        suspend fun add(number: Int): Int { // HOW DO I GET EXCEPTION THROWN HERE?
            eventChannel.send(number)
            return stateChannel.value
        }
    
        init {
            Given("we are in initial state") {
                currentState shouldBe 0
                When("adding 2") {
                    add(2)
                    Then("the state should be 2") {
                        currentState shouldBe 2
                    }
                }
                When("trying to add 1") {
                    Then("we should get an invalid event exception") {
                        val exception = shouldThrow<InvalidEventException> {
                            add(1) // THIS IS MY PROBLEM: java.lang.AssertionError: Expected exception CoroutineExceptionTest.InvalidEventException but no exception was thrown.
                        }
                    }
                }
            }
        }
    }
    • 1
    • 1
  • c

    Colton Idle

    12/10/2019, 8:14 AM
    Is there any reason why I can't
    await()
    a coroutine? I thought I would be able to just define my
    val result = myRetrofitSuspendingCall
    and call
    await()
    on it. It seems like I need to wrap it in an
    async{}
    block before I do, but it seems a little counterintuitive. (I'm still new at coroutines)? Is this async block needed because coroutines themselves still read like synchronous code?
    o
    • 2
    • 9
  • d

    Dmitry Khasanov

    12/10/2019, 12:10 PM
    suspendCancellableTimeoutCoroutine() - cancelled by timeout 1. app crashes
    runBlocking {
    suspendCancellableTimeoutCoroutine()
    }
    2. app doesn't crash
    runBlocking {
    launch {
    suspendCancellableTimeoutCoroutine()
    }
    }
    3. app doesn't crash, but I don't see stacktrace in logcat
    runBlocking {
    val handler = CoroutineExceptionHandler { _, e -> e.printStackTrace() }
    launch(handler) {
    suspendCancellableTimeoutCoroutine()
    }
    }
    4. This is the behavior that I have now, it works as needed
    runBlocking {
    try {
    suspendCancellableTimeoutCoroutine()
    } catch(e: CancellableException) {
    e.printStackTrace()
    }
    }
    Could anyone explain to me 2 and 3, please?
    y
    • 2
    • 6
  • a

    Alireza

    12/10/2019, 2:55 PM
    Hi, is possible to use coroutines as
    EventBus
    ? i found this gist: https://gist.github.com/svenjacobs/57a21405b2dda4b62945c22235889d4a , but
    filter
    operator of
    openSubscription()
    is mark as deprecated!, is there any better sample code?
    a
    b
    g
    • 4
    • 6
  • a

    akshay_b

    12/11/2019, 7:47 AM
    Hi, I have the following suspended function, which I want to expose as Java APIs(blocking) and Kotlin API(non-blocking) with same method name.
    suspend fun getStoreMapping(country: String): List<Store> {
        return client.getStoreMapping(country).stores
    }
    Currently, the only option I have is to use different method name, which calls the suspended function in
    runBlocking {}
    like below -
    fun getStoreMappingInJava(country: String): List<Store> {
        return runBlocking { client.getStoreMapping(country).stores }
    }
    o
    g
    a
    • 4
    • 7
  • k

    Kevin Gorham

    12/11/2019, 1:14 PM
    This does not behave as I'd expect. Can anyone explain why the first example does not print
    output
    but the second, similar, example does? No permutation of yield, delay or sleep seems to get
    output
    to print in Example 1. Example 1 (always prints
    start stop
    ):
    @Test
        fun testUnexpectedBehavior() = runBlocking {
            print("start")
            captureScope()
            scope.launch {
                print(" output")
            }
            print(" stop")
        }
    
        lateinit var scope: CoroutineScope
        suspend fun captureScope() = coroutineScope {
            scope = this
        }
    Example 2 (always prints `start output stop`:
    @Test
        fun testExpectedBehavior() = runBlocking {
            print("start")
            coroutineScope {
                launch {
                    print(" output")
                }
            }
            print(" stop")
        }
    t
    b
    • 3
    • 3
  • a

    Alessandro Diaferia

    12/11/2019, 3:10 PM
    Hi all. I’ve got a
    CoroutineScope
    that works off an IO dispatcher (
    <http://Dispatchers.IO|Dispatchers.IO>
    ) and now I’d need to use a class from an external library that is not thread-safe and requires a heavy initialization phase (in the order of a few seconds) per thread. How should I approach this problem? Would I simply initialize one instance and add it to the current
    CoroutineContext
    ? How would its access be regulated to make sure there is no concurrent multi-thread access from the various coroutines spread across multiple threads (I assume
    <http://Dispatchers.IO|Dispatchers.IO>
    spans across multiple threads). Any help appreciated.
    b
    k
    • 3
    • 6
  • i

    igor.wojda

    12/11/2019, 4:23 PM
    Is there any way to “connect” to existing running coroutine job and wait for the result? Case: Let’s say I have the same instance of repository injected into multiple different classes (
    client A
    ,
    client B
    ). Now
    client A
    calls
    repository.getUserData()
    and this method internally loads data from network. While request is going
    cliebt B
    also calls
    repository.getUserData()
    on the same instance of repository. Can we detekt that network call is in progress and somehow wait for it to finish and return data to both clients?
    // Client A:
    CoroutineScope(<http://coroutineContentProvider.IO|coroutineContentProvider.IO>).launch {
        reository.getUserData()
    }
    
    // Client B:
    CoroutineScope(<http://coroutineContentProvider.IO|coroutineContentProvider.IO>).launch {
        reository.getUserData()
    }
    
    class Repository() {
        private val job: Job? = null
    
        suspended fun getUserData() {
            if(job != null) {
                // job is already runned by other client 
                // can I some how "connect" (wait fo the result) to this job
                // instead of proceding and making new network request
            }
    
            job = CoroutineScope(<http://coroutineContentProvider.IO|coroutineContentProvider.IO>).launch {
                // make network call and return client data
                // return network data
            }
        }
    }
    b
    • 2
    • 4
  • d

    David Glasser

    12/11/2019, 5:37 PM
    I recently upgraded to IntelliJ 2019.3 and to Kotlin 1.3.61, and I'm starting to see a ton of "Inappropriate blocking method call" inspections. They mostly seem to be inside
    suspend
    functions where they call other
    suspend
    functions I wrote, so they seem like they may be spurious. Does anyone have any ideas about how to learn more about why these inspections are showing up, to either report a bug or to fix my code if it is in fact bad?
    o
    t
    • 3
    • 10
  • l

    Luis Munoz

    12/11/2019, 9:44 PM
    I want to suspend from calling a function until some variable is set, what is the best way to do that? It is sort of the reverse of how I normally think of a Mutex. Is the best way just to create a mutex that is locked and just try to lock it again, and when my variable is set just unlock it, which will then allow calling the function
    l
    a
    +3
    • 6
    • 8
  • d

    dekans

    12/12/2019, 8:14 AM
    Is there a naming convention for functions returning a
    Flow
    ? (like Async suffix for the ones returning a
    Deferred
    )
    o
    e
    +2
    • 5
    • 11
  • c

    Colton Idle

    12/12/2019, 9:31 AM
    I'm using retrofit to perform two network calls async, and I then await their results. The thing is that I don't know how to do proper exception handling. I thought it would be straight forward, but apparently this isn't working. Is there something with async that I have to do differently?
    val work1 = async { getThingsDone(43) }
    val work2 = async { getThingsDoneAgain(123) }
    
    if (work1.await().isSuccessful && work2.await().isSuccessful) {
    //do my thing
    } else {
    //failure message
    }
    Now with that block above I saw that I was sometimes getting some IOException, and so I wrapped it all in a try/catch.
    try {
    val work1 = async { getThingsDone(43) }
    val work2 = async { getThingsDoneAgain(123) }
    
    if (work1.await().isSuccessful && work2.await().isSuccessful) {
    //do my thing
    } else {
    //failure message
    }
    } catch (e: IOException){
    //network failure message
    }
    But I still get the IOException. It's as if the try/catch doesn't work.
    t
    o
    +2
    • 5
    • 26
  • t

    tseisel

    12/12/2019, 10:52 AM
    Currently, when using
    flow.produceIn(aScope)
    , if the source flow terminates with an exception then the
    produce
    coroutines fails and cancels the scope and its parent. Wouldn't it be better if it only cancelled the resulting
    ReceiveChannel
    ?
    b
    • 2
    • 1
  • j

    John

    12/12/2019, 6:46 PM
    What’s the right way to hold a coroutine until a listener is called? I.e. something like:
    fun suspend getCar(): Car {
        val returnedCard
        fetcher.getCar({ car ->
           returnedCar = car 
        })
        // await while car is fetched ???
        return returnedCar
    }
    r
    p
    • 3
    • 4
  • m

    Marko Mitic

    12/12/2019, 8:34 PM
    Hi, I need a CoroutineDispatcher on Android that will make
    delay
    wait for given real time, not CPU time. I'm assuming that default implementation doesn't take CPU sleep into account, I'm I right? If during 5min delay CPU sleeps for 15 min, will delay effectively take 20min?
    o
    s
    • 3
    • 10
  • p

    Patrick

    12/13/2019, 8:48 AM
    Is there a way to get the parent context of a coroutine (the context the coroutine has been launched from)?
    o
    l
    u
    • 4
    • 18
  • p

    Patrick

    12/13/2019, 10:05 AM
    What is the error I am making here? The coroutine should run on the main thread as seen by the log output. However I still get the exception that I can’t use a Toast here.
    Code + Logs
    t
    • 2
    • 2
  • d

    Daniel Lukic

    12/13/2019, 10:56 AM
    what is the best way to track down something like this? (android app)
    ime  D  Shutting down VM
         E  FATAL EXCEPTION: main
         E  Process: com.dhl.lps.consumer.debug, PID: 18730
         E  kotlinx.coroutines.JobCancellationException: Job was cancelled; job=StandaloneCoroutine{Cancelling}@48c8a44
    we have scopes like
    MainScope() + CxExceptionHandler(..)
    with
    launch { .. }
    consistently. no
    async
    for now. so this seems to be some weird/interesting edge case.. 🙂 any pointers on how to track this thing down? 🤔
    v
    • 2
    • 3
  • c

    cak

    12/13/2019, 11:43 AM
    👋 all! I'm new to Kotlin and I am trying to use coroutines and Swing - the above code sort of works, but doesn't update the table ui until it has been pressed a few times - am I doing this right? https://github.com/TypeError/Bookmarks/blob/177801633a1e8f51ae8aad2c5e1bf034b83a9faa/src/BookmarkTab.kt#L158
    d
    • 2
    • 3
Powered by Linen
Title
c

cak

12/13/2019, 11:43 AM
👋 all! I'm new to Kotlin and I am trying to use coroutines and Swing - the above code sort of works, but doesn't update the table ui until it has been pressed a few times - am I doing this right? https://github.com/TypeError/Bookmarks/blob/177801633a1e8f51ae8aad2c5e1bf034b83a9faa/src/BookmarkTab.kt#L158
d

diesieben07

12/13/2019, 11:46 AM
First thing I noticed is that you are accessing
repeatInTable
(which is a Swing component) from the IO thread. Swing is not threadsafe. Then, instead of launching another job using
launch
, you can just use
withContext(Dispatchers.Swing) {
}
c

cak

12/13/2019, 12:48 PM
Thanks so much! I'll give those a try!
Is there also a way to have a timeout and exit the thread (or coroutine, all new to me) and update the UI? I think the network call may be hanging the update. Also will the withContext execute after the network call above it it returns or concurrently? If concurrent, can we get it to wait before it updates?
View count: 4