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

    darkmoon_uk

    09/12/2019, 11:02 AM
    Any word when
    Flow
    and associated API's are likely to leave 'experimental'? Is it too bad to admit I've got production code peppered with Experimental annotations? At least I haven't found bugs with it yet! 😅
    e
    s
    • 3
    • 4
  • d

    darkmoon_uk

    09/12/2019, 1:48 PM
    Excited to finally be using coroutines on a real life project! 😒uspend: introduction to my team of four devs has been largely smooth; I encouraged them all to watch @elizarov’s inaugural (and excellent) presentation, now we're diving in... utterly crazy to be making our first use of coroutines and Flows on a serious production code with a tight deadline of 2 weeks but what a great way to learn! I'd say there has been less friction than when I introduced RxJava to the same team around 2 years ago; the tighter integration with the language means they're more able to be flexible with which features they use and when.
    👍 2
    r
    m
    f
    • 4
    • 6
  • i

    igorvd

    09/12/2019, 4:29 PM
    Is there an easy way to use Espresso idling resources with coroutines? I'm not sure how I can make sure that my espresso tests waits until all coroutines finish running.
    l
    m
    • 3
    • 5
  • h

    hooliooo

    09/12/2019, 8:38 PM
    Hi there is this the correct implementation of coroutineScope? Will this call the
    someSuspendHttpRequestWithKtor
    in parallel from the
    map
    call?
    suspend fun someCRUDMethod(models: List<MyModel>) {
        val myModels = coroutineScope {
            async {
                models.map { myAPI.someSuspendHttpRequestWithKtor(it.id) }
            }
        }
        val myListOfModels = myModels.await()
        ....
    }
    s
    • 2
    • 14
  • m

    myanmarking

    09/13/2019, 12:45 PM
    class TestExample {
    
        class Example {
            var counter: Int = 0
    
            fun startCounter() {
                val coroutineScope = CoroutineScope(Dispatchers.Unconfined)
    
                coroutineScope.launch {
                    while (counter <= 100) {
                        counter += 1
                        delay(100)
                    }
                }
            }
        }
    
        @Test
        fun `test 1`() = runBlockingTest {
            val example = Example()
            example.startCounter()
            Assert.assertEquals(1, example.counter)
            advanceTimeBy(150)    // fails
            // Thread.sleep(150) // works
            Assert.assertEquals(2, example.counter)
        }
    }
    p
    g
    • 3
    • 11
  • p

    Paul Woitaschek

    09/14/2019, 7:16 AM
    Is it somehow possible to await a continuation?
    a
    o
    +2
    • 5
    • 31
  • v

    vineethraj49

    09/14/2019, 9:50 AM
    Hi, 1. when does a Job get completed? once all the `.launch`ed job children get completed? 2. can a job indefinitely block a parent context if it is still .isActive`
    Untitled
    e
    • 2
    • 22
  • b

    Bilagi

    09/14/2019, 4:44 PM
    Retrofit 2.6.0
    suspend functions doesn’t support null response body types. Is there any work around for this ?
    l
    • 2
    • 2
  • s

    scottiedog45

    09/14/2019, 6:21 PM
    If I’m using this
    liveData
    block, do I need to scope it to
    viewModelScope
    , or is that handled automatically? Specifically I’m concerned about cancelling the job, does that still need to be done with this method?
    val testLangLiveData : LiveData<String?> = liveData {
            viewModelScope.launch {
                try {
                    emit(repository.getUser().data.attributes?.locale)
                } catch (e: Exception) {
    
                }
            }
        }
    a
    • 2
    • 2
  • v

    vineethraj49

    09/15/2019, 1:11 PM
    so, “explicit concurrency” suggests:
    every function that is declared as extension on CoroutineScope returns immediately, but performs its actions concurrently with the rest of the program.
    i.e.,
    suspend fun
    is a non-blocking, waiting function; while functions declared on
    CoroutineScope.foo
    are non-blocking, “spawn something else concurrently” function; what is the idiomatic way to do this in a class that already inherits
    CoroutineScope
    ?
    d
    • 2
    • 4
  • k

    Kroppeb

    09/15/2019, 2:27 PM
    Is there a way to use a select expression with something that's not a channel?
    d
    • 2
    • 9
  • m

    Mark

    09/16/2019, 8:33 AM
    After updating coroutines (android) from 1.2.1 to 1.3.0 (same if 1.3.1) I’m getting this crash:
    "kotlinx.coroutines.channels.ClosedSendChannelException: Channel was closed"
    when calling
    SendChannel.send
    (note: I’m using
    produce
    to build the channel). I’ve isolated the cause to be this upgrade. I couldn’t find anything relevant in the release notes: https://github.com/Kotlin/kotlinx.coroutines/releases . Any tips on how to investigate what could be causing this, please?
    o
    l
    +2
    • 5
    • 16
  • d

    Dico

    09/16/2019, 9:15 AM
    Is there a good reason why
    SendChannel.offer
    throws instead of returning
    false
    ? If so, why is there not an equivalent that never throws?
    v
    • 2
    • 3
  • t

    tseisel

    09/16/2019, 10:15 AM
    Is there something similar to RxJava
    TestObserver
    to test coroutines
    Flow
    ?
    g
    m
    +5
    • 8
    • 15
  • g

    groostav

    09/16/2019, 6:57 PM
    hmm. I have producers that will out-produce a consumer. I want the producers to fill a buffer and then over-write the oldest data when they produce on a full buffer. The consumer should always get the newest added element. I think what I'm looking for is a kind of circular linked list. Anybody know of a package with such a data structure and/or a way I can butcher
    java.util.concurrent
    or similar to give me this?
    w
    r
    b
    • 4
    • 12
  • s

    scottiedog45

    09/16/2019, 10:13 PM
    I’m using this for basically all of my viewModels- is there a more concise/kotlinesque way to write the coroutine + error handling + networking logic, and should I be using a specific dispatcher for networking?
    fun updateUserLang(user: UpdateUser) {
            viewModelScope.launch {
                try {
    
                    val lang = repository.updateUser(user).data.attributes!!.locale
    
                    _networkCallSuccess.postValue(Pair(lang!!, true))
    
                } catch (e: HttpException) {
                    println("error: ${e.localizedMessage}")
                }
            }
        }
    d
    • 2
    • 2
  • r

    rkeazor

    09/16/2019, 11:41 PM
    how do you guys test suspendCancellableCorourtine.
    d
    g
    • 3
    • 21
  • a

    Adriano Celentano

    09/17/2019, 7:54 AM
    unfortunately i dont get the full stacktrace of my exception in my coroutine, are there better solutions than what i improvised so far ?
    val trace = Thread.currentThread().stackTrace
        val handler = CoroutineExceptionHandler { _, throwable ->
            throwable.stackTrace += trace
            result(Result.failure(throwable))
        }
    g
    • 2
    • 7
  • t

    Tuan Kiet

    09/17/2019, 8:08 AM
    does kotlin coroutine suit for fire and forget scenario, for example, I want to fire 1000 network request in 5 minutes, something like
    viewModelScope.launch{}
    but don’t care about the result. When a coroutine is finished, does it goes away or it stays in memory?
    d
    a
    g
    • 4
    • 6
  • c

    Colton Idle

    09/17/2019, 1:40 PM
    Just trying to play around with coroutines to mock out what a long running DB operation or network call could look like if I wanted to Toast the result of it. I'm really just learning Kotlin and coroutines so they are crude examples. Can anyone tell me what's wrong about my coroutine here? I'm finding it coroutines tough to understand.
    fun button1Clicked() {
    GlobalScope.launch {
    Toast.makeText(this@MainActivity, doSomethingLong(), Toast.LENGTH_LONG).show()
    }
    Toast.makeText(this@MainActivity, "Hello", Toast.LENGTH_LONG).show()
    }
    
    suspend fun doSomethingLong(): String =
    withContext(Dispatchers.Default) {
    delay(3000)
    return@withContext "World"
    }
    e
    a
    g
    • 4
    • 10
  • d

    dave08

    09/17/2019, 3:22 PM
    Is the only way to make a step in a flow concurrent by using flatMapMerge? I have a transform step that can be made concurrent (it uses network requests), can I just use a withContext on it?
    d
    • 2
    • 7
  • c

    Casey Brooks

    09/17/2019, 4:54 PM
    Is this the proper way to detect if a coroutine has been cancelled? For context, I was trying to just catch and handle failures, and found I was catching `CancellationException`s too, and I’m not sure if this is how I should be handling it
    try {
        coroutineScope {
            next()
        }
    } catch (e: Exception) {
        if(e !is CancellationException) {
            onCancelled()
        }
        else {
            onFailure()
        }
    }
    w
    • 2
    • 1
  • s

    Seri

    09/17/2019, 7:53 PM
    Is there a standard operator for combining asynchronous flows that share a supertype? As each value comes in from the source Flows, I want them to immediately join into the same downstream flow. At the moment, I have the following implementation:
    fun <T> List<Flow<T>>.join() = channelFlow {
        for (flow in this@join) {
            launch { flow.collect {
                send(it)
            }}
        }
    }
    v
    a
    e
    • 4
    • 12
  • a

    Allan Wang

    09/17/2019, 11:51 PM
    is there any specific way to wait for pending coroutines in an Android emulator test? Is it fine to use runBlocking to wait?
    g
    • 2
    • 1
  • a

    Allan Wang

    09/18/2019, 12:18 AM
    On that note as well, is there a good way to "pause" launches and have them run at a later time during testing? For instance, if we are loading an item and showing a view until we get our data, and we now mock our data to return near instantly, how can we keep the test from being flaky?
    g
    d
    • 3
    • 2
  • n

    nomad

    09/18/2019, 11:41 AM
    We are looking into an issue where our CPU usage goes way up when switching from an old version of ktor to a new one. We have profiled extensively, and cannot find any code in ktor that leads to this performance regression. All we can think of is ktors increasing use of coroutines since version 1.0+, all of which show this regression. I have attached a screen dump from our profiler, I am mainly wondering if it is expected that we spend ~30% in the CoroutineScheduler$Worker.run method? When profiling the older versions of ktor, we see the same performance from the other methods just without this ~30% chunk. Is this unavoidable overhead from coroutines? A bad reporting from the profiler? or am I just missing something? We are also seeing a big increase in kernel mode cpu usage, nearly doubling with the same workload on ktor 1.0+ versions. This is with ktor 1.2.3 on kotlin 1.3.41
    r
    a
    +2
    • 5
    • 10
  • m

    Mohamed Hamdan

    09/18/2019, 9:36 PM
    Hi all, Is there any testable error handling with coroutines without try catch?
    e
    • 2
    • 1
  • z

    zak.taccardi

    09/19/2019, 1:35 AM
    is it possible to get a channel to drop items (have
    .offer(item)
    return
    false
    ) if no one is receiving?
    d
    r
    • 3
    • 3
  • v

    vineethraj49

    09/19/2019, 9:26 AM
    since
    <http://Dispatchers.IO|Dispatchers.IO>
    shares threads with
    Dispatchers.Default
    , is it possible that if there are too many IO requests, coroutines spawned on
    .Default
    will be starved?
    g
    • 2
    • 1
  • k

    Kroppeb

    09/19/2019, 12:51 PM
    How do I convert this into less janky and actually working code
    😕 1
    m
    p
    +2
    • 5
    • 36
Powered by Linen
Title
k

Kroppeb

09/19/2019, 12:51 PM
How do I convert this into less janky and actually working code
😕 1
This is the log btw
m

marstran

09/19/2019, 12:57 PM
So, what are you trying to do?
k

Kroppeb

09/19/2019, 1:04 PM
I'm reading raw bytes from a ByteReadChannel and if i got a cipher i encrypt and then send those bytes int a different ByteChannel
the problem is that ByteChannel#Read requires a normal lambda and not a suspending one which is causing all the problems
I fixed it by moving the Job initialiser outside of the while loop 🤦‍♂️
But still the code looks jank
I'm extracting it to a extensionfunction for the time being
m

marstran

09/19/2019, 1:11 PM
So the read-lambda is a callback right?
k

Kroppeb

09/19/2019, 1:11 PM
yeah
m

marstran

09/19/2019, 1:12 PM
Ok, then you should convert it to a coroutine with the
suspendCoroutine
function. Check out this article: https://medium.com/@elizarov/callbacks-and-kotlin-flows-2b53aa2525cf
p

Paulius Ruminas

09/19/2019, 1:12 PM
Which functions are suspending in launch? Maybe you could use a channelFlow instead of the nullable Job to pass the data
k

Kroppeb

09/19/2019, 1:12 PM
What do you mean?
I'm writing to a second byteChannel
those writes are suspending
in the future it might be converted into a channel of a certain type but that requires some refactoring and wrappers and i first want my code working
I'm guessing my question is: Is there a variant for read that allows supension?
m

marstran

09/19/2019, 1:15 PM
So something like
suspend fun ByteChannel.read(): ByteBuffer = suspendCoroutine { continuation -> 
  read { continuation.resume(it) }
}
k

Kroppeb

09/19/2019, 1:18 PM
doesn't seem to work
this also feels janky
m

marstran

09/19/2019, 1:49 PM
Weird error you get in the first one. You said
read
isn't suspending, right?
Could you try renaming your function to
readSuspending
?
k

Kroppeb

09/19/2019, 1:50 PM
read is suspending
m

marstran

09/19/2019, 1:51 PM
The original ByteChannel.read or the one you wrote?
k

Kroppeb

09/19/2019, 1:51 PM
both
m

marstran

09/19/2019, 1:52 PM
Oh, ok. Then you won't need the suspendCoroutine thing.
What library is
ByteChannel
from?
Seems weird to me that a suspending function has a callback as a parameter
k

Kroppeb

09/19/2019, 2:04 PM
kotlin.coroutines.io.ByteReadChannel#read
e

Evan R.

09/19/2019, 2:26 PM
I think the real question here is why are you doing a second nested launch if you just want to wait for the coroutine to complete before starting the next loop iteration?
k

Kroppeb

09/19/2019, 2:34 PM
I was doing that cause i didn't know how to do it otherwise
it's gone now
e

Evan R.

09/19/2019, 2:48 PM
Alright, should be fine then. I assume that since
read
is a suspending function it will wait until new bytes come into the channel before writing out to the output channel.
c

Colton Idle

09/20/2019, 3:29 AM
What's your code look like now @Kroppeb?
k

Kroppeb

09/20/2019, 10:23 AM
https://kotlinlang.slack.com/archives/C1CFAFJSK/p1568900152090700?thread_ts=1568897501.085700&amp;cid=C1CFAFJSK
View count: 7