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

    kawmra

    09/04/2019, 3:56 PM
    Hi. Is there any zero-capacity channels that always can
    send
    without suspension? It seems
    Channel(0)#send
    will suspend unless any receivers are consuming values. It is okay if values will be lost when no receivers are consuming.
    b
    j
    +2
    • 5
    • 6
  • e

    elizarov

    09/05/2019, 4:57 AM
    🎉
    kotlinx.coroutines
    version
    1.3.1
    is released with several minor fixes. Note: Kotlin/Native artifacts are now published with Gradle metadata format version 1.0, so you will need Gradle version 5.3 or later to use this version of kotlinx.coroutines in your Kotlin/Native project. Full list of changes: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.3.1
    😒uspend: 20
    👍 5
    🎉 20
    g
    • 2
    • 3
  • s

    svenjacobs

    09/05/2019, 10:47 AM
    What is the difference between
    channelFlow
    and
    callbackFlow
    ? Both have the same signature except latter is
    inline
    . Is this the only difference?
    d
    s
    • 3
    • 7
  • d

    David Glasser

    09/05/2019, 2:48 PM
    I am writing a suspend-based wrapper around Caffeine's AsyncLoadingCache, which natively understands cache-loading functions that return CompletableFutures. My class has a
    get()
    method which launches a coroutine using
    CoroutineScope.future{}
    . That coroutine should not be scoped to the
    get()
    method's lifetime, because if
    get()
    is called concurrently with the same key, both
    get()
    calls will end up waiting on the same CompletableFuture, so cancelling the first coroutine shouldn't cause the second coroutine to fail. So I'm currently passing a
    CoroutineScope
    into the constructor of the cache and using that to launch the `future`s. However, my current implementation means that if any of the calls inside
    future{}
    fail, the long-lived CoroutineScope associated with the cache is canceled, which I don't want. What I want basically is a supervisor scope nested inside the passed-in CoroutineScope, created at cache construction time. But
    supervisorScope
    doesn't seem to be what I want — I can't call that at cache construction time because I don't want to actually wait before returning like a supervisorScope does! Is there some other API I should be using here? I feel like maybe the answer is
    SupervisorJob()
    but I am still kinda confused about the distinction between Job and CoroutineScope — I can make a
    SupervisorJob(coroutineScope.coroutineContext[Job])
    but I'm confused about how to extract a CoroutineScope from it that I can use for launching coroutines.
    s
    d
    s
    • 4
    • 60
  • j

    Jan Stoltman

    09/05/2019, 2:51 PM
    Is there any good explanation about how the BroadcastChannel's buffer works? In my tests it seems like it's ignored and my receiver receives only values sent after its subscription.
    w
    z
    • 3
    • 3
  • d

    David Glasser

    09/05/2019, 6:52 PM
    In a test, I have:
    cache.getIfPresentAsync("x").let { deferred ->
    				assertNotNull(deferred)
    				assertTrue(deferred.isCompleted)
    				assertEquals(42, deferred.await())
    			}
    IntelliJ is giving me an inspection "Deferred result is never used" on the word assertNotNull. Is there actually anything wrong with my code? It looks like the inspection goes away if I delete the assertNotNull line and change the assertTrue to
    deferred!!.isCompleted
    , but I'm wondering if I'm missing something
    j
    • 2
    • 3
  • z

    zak.taccardi

    09/06/2019, 12:56 AM
    Obviously this is an anti-pattern, but how would one go about converting a
    Flow<T>
    into a
    ReceiveChannel<T>
    ? I’ve tried the following so far, but it’s deadlocking
    @Suppress("DeprecatedCallableAddReplaceWith")
    @Deprecated("You should be using Flows, not channels.")
    fun <T> Flow<T>.collectAsReceiveChannel(scope: CoroutineScope): ReceiveChannel<T> {
        val flow = this
    
        val channel = Channel<T>()
    
        val flowJob = scope.launch {
            flow
                .onEach { item -> channel.send(item) }
                .collect()
        }
    
        channel.invokeOnClose {
            flowJob.cancel()
        }
    
        return channel
    }
    l
    z
    • 3
    • 2
  • s

    svenjacobs

    09/06/2019, 6:01 AM
    When dealing with
    callbackFlow
    , I now saw two different "official" approaches of how to deal with upstream exceptions returned by the wrapped callback. Should I either call
    close(exception)
    or
    cancel(CancellationException("Error occurred", exception))
    ?
    👀 1
    d
    • 2
    • 1
  • d

    davide

    09/06/2019, 7:20 AM
    Hi All! For exercise only, I'm trying to replace Project Reactor with Coroutine. There is some article/blog post that can help me in this task? Any suggestion will be appreciated 🙂
    s
    l
    • 3
    • 15
  • z

    Zach Klippenstein (he/him) [MOD]

    09/06/2019, 6:26 PM
    I feel like there have been a lot of questions recently about the difference between
    callbackFlow
    and
    channelFlow
    (e.g. https://github.com/Kotlin/kotlinx.coroutines/issues/1500). The rationale for having two separate aliases for the same function is that “have different names to tailor their docs the the speicific use-case and to enable the code using them to convey your intention.” Is the distinction between them really providing enough value to justify all the confusion they seem to be creating? It seems like the documentation could be merged, and I don’t fully understand how much value is really added by making “intent” clearer – in what case would choosing one over the other actually make code significantly clearer? If callbacks are being used, it will be apparent in the code because there’ll be lambdas and
    addListener
    calls everywhere. Additionally, RxJava users have gotten used to using
    Observable.create { }
    for integrating with callback-based APIs even though it doesn’t have “callback” in the name anywhere.
    p
    • 2
    • 3
  • m

    matt tighe

    09/06/2019, 7:53 PM
    how can i unit test flows? the following never completes
    @Test
        fun listCanBeObserved() = runBlocking {
            dao.insert(thing)
    
            val data: List<Thing> = dao.observeAll().single()
            val expected = Thing()
            assertEquals(expected, data)
        }
    but if I manually collect each emission I can see the assertion is hit successfully in debug mode
    fun listCanBeObserved() = runBlocking {
            dao.insert(thing)
    
            val data: List<Thing> = dao.observeAll().collect {
                val expected = Thing()
                assertEquals(expected, data)
            }
        }
    but then the test will never complete
    d
    • 2
    • 7
  • r

    Rafa

    09/07/2019, 3:31 PM
    GlobalScope.launch {
                Log.d("rafa", "thread:${Thread.currentThread()}") // this prints Thread[DefaultDispatcher-worker-1,5,main]
                someTextView.text = "new test"
            }
    Does anyone know why that doesn't crash ^? Even though it's changing text in the UI on a worker thread?
    s
    a
    • 3
    • 6
  • d

    darkmoon_uk

    09/08/2019, 1:46 AM
    Is there an (idiomatic) way to iterate over
    Iterable<Deferred<T>>
    ?
    s
    g
    • 3
    • 2
  • s

    Sangeet

    09/08/2019, 5:16 PM
    @ExperimentalCoroutinesApi // Since 1.2.1, tentatively till 1.3.0
    public suspend inline fun <T> ObservableSource<T>.collect(action: (T) -> Unit) =
        openSubscription().consumeEach(action)
    will there be any changes in above method in coming releases ?
    g
    • 2
    • 2
  • a

    Adriano Celentano

    09/09/2019, 2:15 PM
    Each suspend function has exactly one Continuation object, right or wrong ?
    s
    d
    • 3
    • 6
  • d

    Dico

    09/09/2019, 3:53 PM
    I have some code that takes items from a channel and sends them in batches to a HTTP api with ktor. How can I make it detect cancellation and send the remaining accumulated items in a clean way? Pseudo code here:
    private val processor = scope.launch {
            val batch = ArrayList<String>(MAX_BATCH)
            
            suspend fun sendBatch() {
                val payload = batch.joinToString(separator = "\n")
                batch.clear()
                return sendPayload(payload)
            }
            
            try {
                while (isActive) {
                    batch.add(hitChannel.receive())
                    if (batch.size == MAX_BATCH) {
                        sendBatch()
                    }
                }
            } finally {
                if (batch.isNotEmpty()) {
                    sendBatch()
                }
            }
        }
    I expect that final
    sendBatch
    will throw exception because coroutine no longer
    isActive
    . I can't do
    withContext(NonCancellable)
    either at that point.
    d
    • 2
    • 34
  • m

    mingkangpan

    09/09/2019, 4:00 PM
    hey guys, I am really having a hard time understand the
    BroadcastArrayChannel
    could someone try to explain it to me, especialy in which scenario this channel can be used?
    d
    • 2
    • 7
  • k

    Kroppeb

    09/09/2019, 4:58 PM
    I have the following code but I feel like I'm doing something wrong, mostly in the
    start
    function
    class EncryptionStep{
    	var key: SecretKey? = null
    	val input: ByteWriteChannel get() = _input
    	val output: ByteReadChannel get() = _output
    
    	private val _input = ByteChannel()
    	private val _output = ByteChannel()
    
    	@UseExperimental(InternalAPI::class)
    	fun CoroutineScope.start(encrypted: Pair<ByteReadChannel, ByteWriteChannel>) {
    
    		launch {
    			_input.read{
    				runBlocking{
    					when(val key = key){
    						null -> encrypted.second.writeAvailable(it)
    						else -> encrypted.second.writeAvailable(encryptData(key, it.moveToByteArray()))
    					}
    				}
    			}
    		}
    	}
    }
    
    
    fun CoroutineScope.encryptionStep(encrypted: Pair<ByteReadChannel, ByteWriteChannel>): EncryptionStep {
    	val step = EncryptionStep()
    	
    	with(step){
    		start(encrypted)
    	}
    
    	return step
    }
    d
    • 2
    • 3
  • s

    savrov

    09/09/2019, 7:32 PM
    Hello, with Ktor Client i want to archive secure http requests. The idea is: 1. make a request 2. response code equals to 401 3. stop all other request and make them wait for response from auth endpoint (ex: refresh token) 4. receive new token 5. rerun request from 1 step and resume all “pending” request from step 3. I think I can archive it with
    ConflatedBroadcastChannel
    , but i dont know how to do it. Pls share with your thoughts
    d
    l
    • 3
    • 3
  • r

    rook

    09/09/2019, 10:10 PM
    E/File$object: kotlinx.coroutines.channels.ClosedSendChannelException: Channel was closed
            at kotlinx.coroutines.channels.Closed.getSendException(AbstractChannel.kt:1048)
            at kotlinx.coroutines.channels.AbstractSendChannel.offer(AbstractChannel.kt:166)
            at kotlinx.coroutines.channels.ChannelCoroutine.offer(ChannelCoroutine.kt)
    Untitled.kt
    d
    • 2
    • 3
  • m

    marcinmoskala

    09/10/2019, 7:35 AM
    Why
    runBlocking
    starts by default on a thread named "main" instead of using
    Dispatchers.Default
    ?
    fun main() = runBlocking() {
        print(Thread.currentThread().name) // main
    }
    
    fun main() = runBlocking(Dispatchers.Default) {
        print(Thread.currentThread().name) // DefaultDispatcher-worker-1
    }
    j
    m
    k
    • 4
    • 5
  • e

    Eugen Martynov

    09/10/2019, 8:47 AM
    Probably asked many times already - is there good workshop about coroutines?
    l
    • 2
    • 11
  • r

    rocketraman

    09/10/2019, 4:36 PM
    Trying to understand what does, and does not work, with coroutines exception stack recovery (no debug agent here, just a vanilla 1.3.50 + 1.3.0 environment). If I do this:
    fun main() {
      runBlocking {
          throw Exception("e")
      }
    }
    I see the expected stack with the
    main.runBlocking
    call in the stack. However, if I change the dispatcher to explicitly specify
    Dispatchers.Default
    e.g.
    runBlocking(Dispatchers.Default)
    , then all I see is the
    BaseContinuationImpl.resumeWith
    in the stack, and the resume point. This is doubly weird, because I thought
    Dispatchers.Default
    was... well, the default.
    o
    • 2
    • 11
  • s

    Sergio C.

    09/10/2019, 7:38 PM
    hi all, anyone had this error:
    Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android'
    ?? started happening out of the blue! 😮
    o
    l
    • 3
    • 7
  • v

    vngantk

    09/11/2019, 8:06 AM
    Can anyone tell me what the expected behaviour of the following code is:
    fun main() = runBlocking {
        val job = Job()
        launch {
            delay(1000)
            job.completeExceptionally(IllegalStateException("Failed"))
        }
        try {
            job.join()
            println("foo")
        } catch (e: Exception) {
            println("bar")
            e.printStackTrace()
        }
    }
    d
    b
    • 3
    • 17
  • a

    Adriano Celentano

    09/11/2019, 8:39 AM
    someone else exeperienced exceptions thrown by retrofit which are not caught by the try catch surounding the call ?
    p
    • 2
    • 8
  • v

    vineethraj49

    09/11/2019, 10:04 AM
    is there a good reference worker pool implementation or is the basic fan out example to scale?
    m
    • 2
    • 3
  • d

    dave08

    09/11/2019, 12:56 PM
    Say (just an example) I access an api flow that needs to log in to start working with it, how can I catch the NotLoggedIn exception and then retry the original flow?
    e
    • 2
    • 3
  • c

    curioustechizen

    09/11/2019, 3:41 PM
    This might have been asked before but I could not find much info: Are there any testing utilities for testing Flows? I want to do things like assert the "initial" value of a Flow, perform some action and then assert that the flow emitted another value
    d
    l
    • 3
    • 3
  • a

    Aaron Stacy

    09/11/2019, 6:53 PM
    Hi all, I've got a codebase using coroutines on the JVM (it's a CLI tool), and it got flagged by TSAN (https://wiki.openjdk.java.net/display/tsan/Main) as having a read-after-write race. The code isn't flaky, and it has decent fuzz tests, and TSAN flags the race in
    kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.trySteal()Lkotlinx/coroutines/scheduling/Task
    every time, which leads me to believe there's either a race in the coroutines library that's not affecting my code, or TSAN is unaware of some invariants in coroutines. Does anyone else have experience with TSAN and Kotlin Coroutines? Any idea if this is a bug or a config issue? I'm happy to share the trace if that'd help.
    v
    • 2
    • 4
Powered by Linen
Title
a

Aaron Stacy

09/11/2019, 6:53 PM
Hi all, I've got a codebase using coroutines on the JVM (it's a CLI tool), and it got flagged by TSAN (https://wiki.openjdk.java.net/display/tsan/Main) as having a read-after-write race. The code isn't flaky, and it has decent fuzz tests, and TSAN flags the race in
kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.trySteal()Lkotlinx/coroutines/scheduling/Task
every time, which leads me to believe there's either a race in the coroutines library that's not affecting my code, or TSAN is unaware of some invariants in coroutines. Does anyone else have experience with TSAN and Kotlin Coroutines? Any idea if this is a bug or a config issue? I'm happy to share the trace if that'd help.
v

Vsevolod Tolstopyatov [JB]

09/12/2019, 9:02 AM
Please share the trace (wild guess: it’s line 983 🙂)
a

Aaron Stacy

09/12/2019, 1:32 PM
Not so bad!
106 lines. DM'd you
Our internal copy of the coroutines lib is on https://github.com/Kotlin/kotlinx.coroutines/commit/9a62f27d1fe53552b0838156c17adc3b68dcc585
View count: 7