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

    Tolriq

    03/10/2020, 8:15 AM
    Since DataFlow and share operator seems far away what would the current idiomatic way to have "something" that would support multiple senders to it and conflate to keep the last data and multiple receiver that comes and leaves, but when comes instantly get the last pushed value? (Pushed before it register)
    a
    • 2
    • 1
  • l

    Luis Munoz

    03/10/2020, 3:07 PM
    Has anyone tested coroutines with graalvm? (@elizarov? In particular the native images. I'm getting errors which I can't resolve and sadly I'm going to have to change my code to use reactor.
    Untitled
    e
    m
    • 3
    • 5
  • z

    Zach Klippenstein (he/him) [MOD]

    03/10/2020, 5:37 PM
    There is so much demand for multicasting/sharing support in Flow. Libraries like dropbox/store have their own inline implementations. There are tons of gists of implementations posted on the various coroutine issues. I haven’t seen any libraries published on maven for this though. Has anyone factored any of these out into a library? We’re starting to consider moving from RxJava to Flow in some of our larger codebases and would like to use existing libraries for stuff like this instead of copy/pasting or writing our own implementation of stuff.
    n
    b
    • 3
    • 5
  • m

    Mohamed Ibrahim

    03/10/2020, 5:40 PM
    I wrote an intro for flow, your feedback is more than welcome https://medium.com/@MohamedISoliman/flow-an-intro-for-an-rxjava-user-1b5b6eb21790
    a
    • 2
    • 3
  • n

    niqo01

    03/10/2020, 6:25 PM
    If I am using a library which offers both a synchronous and an asynchronous API to do IO stuff, I am ensure about the pros/cons of using either way: 1. withContext(Dispatchers.IO) { lib.syncAPI() } 2. withContext(Dispatchers.IO) { suspendCancellableCoroutine{ lib*.asyncAPI( object:Listener{ fun onfailure(){} fun onSuccess() ...})}* Option 1 wins on simplicity and I control on my side the thread pool, anything else?
    o
    z
    • 3
    • 4
  • j

    Joe

    03/10/2020, 6:26 PM
    Noticing a performance degradation in a test using coroutines version 1.3.4 vs/ 1.3.3. The test uses Dispatchers.Default and does something like the following: • Launch a coroutine that collects a
    channel.consumeAsFlow()
    • Send a message to the channel that results in another coroutine that sends another message to the channel that results in decrementing a
    CountDownLatch
    • In the main thread, await the
    CountDownLatch
    With 1.3.3, the await took ~180ms. With 1.3.4 its taking ~1.4 seconds. Not sure how this affects the production code yet, but is there a change in 1.3.4 that would explain this?
    🎬 1
    🍿 2
    👀 3
    o
    • 2
    • 3
  • a

    azabost

    03/11/2020, 10:58 AM
    Hi. I’m not sure if it is a bug or I treat the docs too literally so please advise. The doc for
    Flow.launchIn()
    says it is “a shorthand for `scope.launch { flow.collect() }`” but when I compare behaviors in unit tests it is a little different. Having a simple flow:
    private val integersFlow = flow {
            var i = 1
            while(true) {
                delay(100)
                emit(i++)
            }
        }
    and using test scope and dispatcher:
    private val observingScopeJob1 = SupervisorJob()
    private val observingScope1 = CoroutineScope(observingScopeJob1)
    private val testDispatcher = TestCoroutineDispatcher()
    When I do the following:
    @Test
        fun `should receive 10 integers - collect`() = runBlocking {
            var observedIntegers = 0
    
            observingScope1.launch(testDispatcher) {
                integersFlow.collect {
                    observedIntegers++
                }
            }
    
            observedIntegers.shouldEqual(0)
            testDispatcher.advanceTimeBy(1000)
            observedIntegers.shouldEqual(10)
            Unit
        }
    the test passes ✅ but when I convert it into RxJava-style like this:
    @Test
        fun `should receive 10 integers - launchIn`() = runBlocking {
            var observedIntegers = 0
    
            integersFlow
                .onEach { observedIntegers++ }
                .flowOn(testDispatcher)
                .launchIn(observingScope1)
    
            observedIntegers.shouldEqual(0)
            testDispatcher.advanceTimeBy(1000)
            observedIntegers.shouldEqual(10)
            Unit
        }
    the test fails ❎ unless I add an additional
    delay(100)
    before
    testDispatcher.advanceTimeBy(1000)
    which seems very weird to me. Like… why is that needed to delay the main thread in unit test to allow the collecting coroutine to be launched at all?
    l
    • 2
    • 2
  • t

    tseisel

    03/11/2020, 4:44 PM
    How to create a
    CoroutineScope
    that is a child of another ? What I tried:
    val parentScope = ...
    val childScope = parentScope + SupervisorJob()
    
    parentScope.cancel()
    parentScope.isActive // false
    childScope.isActive // true (!!)
    It seems that cancelling the parent does not cancel its children. I guess I'm missing something here...
    b
    j
    d
    • 4
    • 9
  • l

    Luis Munoz

    03/11/2020, 8:24 PM
    What is the proper way make a call back that is called multiple times into a flow? similar to this but that gets called ony once: https://stackoverflow.com/questions/48552925/existing-3-function-callback-to-kotlin-coroutines/48562175#48562175
    Untitled
    s
    • 2
    • 2
  • g

    groostav

    03/11/2020, 9:16 PM
    omg, i thought i knew, I thought knew what concurrency hell was, i thought i could outsmart it. I failed. Now here i am. At least i have kotlinx-coroutines on my classpath?
    textField.debouncedAsTyping(): Flow<Change<String, String>>
    seemed like such a good idea, but back pressure/cancellation is kicking my butt.
    d
    • 2
    • 1
  • r

    rrva

    03/11/2020, 9:50 PM
    Hello. I am using asCompletableFuture as a bridge between coroutines and futures for code where I want to benefit from ktor client being able to run many active connections. In a small example, when errors occur the completablefuture never completes, not even with exception. How do I let the exceptions that occur bubble up correctly? https://github.com/rrva/ktor-client-connection-leak/blob/master/src/main/kotlin/se/rrva/Client.kt I am expecting ”Done with all” to be printed on each run
    b
    • 2
    • 5
  • m

    Mikael Alfredsson

    03/12/2020, 8:45 AM
    Is there any nice class that can be used as a replacement for android LocalBroadcastManager? like a conflated channel but without any “memory” not even the last sent message?
    b
    a
    • 3
    • 19
  • o

    Ofir Bar

    03/12/2020, 8:57 AM
    message has been deleted
    e
    d
    • 3
    • 13
  • v

    vineethraj49

    03/12/2020, 11:18 AM
    if I don't await on a
    GlobalScope.async
    does it get GC'ed allow the stuff being referenced in it get GC'ed?
    e
    • 2
    • 1
  • g

    gotoOla

    03/12/2020, 1:32 PM
    Hi! I have a class which looks like this
    class MyQueueProcessor: CoroutineScope by CouroutineScope(<http://Dispatchers.IO|Dispatchers.IO>) {
        suspend fun start() {
            pollMessages()
            processors.addAll(
                (1..5).map {
                    launchMessageProcessor()
                }
            )
        }
        
        suspend fun pollMessages() = launch {
           while(true) {
              val messages = //... get messages from a queue
              internalChannel.send(messages)
           }
        }
        
        suspend fun launchMessageProcessor() = launch {
            for (messages in internalChannel) {
                // process each 'messages'
            }
        }
    
    }
    but for both pollMessages and launchMessageProcessor I get "Ambiguous coroutineContext due to CoroutineScope receiver of suspend function". How should I interpret this? Is it because suspend fun start() is public and you inherit the coroutineContext from the caller? Since I extend CoroutineScope, the launch and async stuff I use should run on that scope with that dispatcher (IO) right?
    d
    e
    • 3
    • 9
  • r

    rahulrav

    03/12/2020, 3:44 PM
    Cross-point from the #ktor channel (https://kotlinlang.slack.com/archives/C0A974TJ9/p1584027549237200)
    e
    • 2
    • 9
  • s

    Shawn Karber_

    03/12/2020, 8:19 PM
    and no matter what I do, the content variable at the bottom, whether its async, launch, runBlocking, etc. none of them are able to be resolved
    o
    l
    • 3
    • 14
  • c

    charlesmuchene

    03/13/2020, 1:31 PM
    https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/04_Suspend “Coroutines are computations that run on top of threads and can be suspended. By saying “suspended”, we mean that the corresponding computation can be paused, removed from the thread, and stored in memory. When the computation is ready to be continued, it gets returned to a thread (but not necessarily to the same one).” Who works on the computation while it’s suspended? Another thread? Kotlin std library thread? I shouldn’t care?? 🤔 What am I missing on how coroutines work?
    s
    e
    l
    • 4
    • 27
  • m

    myanmarking

    03/13/2020, 6:32 PM
    is there any throttle operator for flow ?
    o
    s
    +3
    • 6
    • 16
  • m

    Mohamed Ibrahim

    03/13/2020, 8:48 PM
    I’m trying to create a flow from an EditText change in Android, I’m using
    flow {…}
    builder, So I’m creating a watcher inside it here is the code, my question is how I clear inner listeners when flow canceled ?
    fun EditText.textChangesFlow(): Flow<TextViewTextChangeEvent> {
        flow<TextViewTextChangeEvent> {
            val watcher = object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    emit(TextViewTextChangeEvent(s.toString()))
                }
    
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                }
    
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }
            }
            addTextChangedListener(watcher)
             //how to call this when flow is canceled or finished
            //removeTextChangedListener(watcher)
    
        }
    }
    s
    k
    +2
    • 5
    • 10
  • a

    Andrew

    03/14/2020, 4:13 AM
    Is there a way to use synchronized() with coroutines? I have a need for several short running coroutines/threads to synchronize access to another function that gets data. Synchronization is needed since the first call is over http then cached locally, to prevent redundant web requests.
    z
    t
    k
    • 4
    • 5
  • m

    Mohamed Ibrahim

    03/14/2020, 3:05 PM
    shouldn’t be gone when converting it to Flow and use
    launchIn()
    ?
    o
    • 2
    • 6
  • j

    JP

    03/16/2020, 9:37 AM
    https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/05_Concurrency
    Run the code and check the log; we can see that all the coroutines still run on the main UI thread. We haven’t yet employed multithreading in any way, but already we have the benefits of running coroutines concurrently!
    It’s very easy for us to change this code to run “contributors” coroutines on different threads from the common thread pool. Specify 
    Dispatchers.Default
     as the context argument for the 
    async
     function:
    async(Dispatchers.Default) { ... }```
    I’m sort of confused. If I don’t specify a dispatcher in the argument for
    async
    function, isn’t the default dispatcher
    Dispatchers.Default
    ? Yet, I did see the logs change from
    147 [AWT-EventQueue-0] INFO  Contributors - Clearing result
    2251 [AWT-EventQueue-0 @coroutine#1] INFO  Contributors - kotlin: loaded 54 repos
    2678 [AWT-EventQueue-0 @coroutine#7] INFO  Contributors - kotlin-benchmarks: loaded 7 contributors
    ...
    to
    164 [AWT-EventQueue-0] INFO  Contributors - Clearing result
    2172 [AWT-EventQueue-0 @coroutine#1] INFO  Contributors - kotlin: loaded 54 repos
    2527 [DefaultDispatcher-worker-5 @coroutine#10] INFO  Contributors - anko-example: loaded 2 contributors
    2621 [DefaultDispatcher-worker-5 @coroutine#9] INFO  Contributors - kotlinx.html: loaded 15 contributors
    ...
    But when I read the comments in the source code of
    Builders.common.kt
    , it was stated like this:
    * Coroutine context is inherited from a [CoroutineScope], additional context elements can be specified with [context] argument.
     * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
     * The parent job is inherited from a [CoroutineScope] as well, but it can also be overridden
     * with corresponding [context] element.
    and in
    Dispatchers.kt
    , it was stated:
    /**
         * The default [CoroutineDispatcher] that is used by all standard builders like
         * [launch][CoroutineScope.launch], [async][CoroutineScope.async], etc
         * if no dispatcher nor any other [ContinuationInterceptor] is specified in their context.
         *
         * It is backed by a shared pool of threads on JVM. By default, the maximal level of parallelism used
         * by this dispatcher is equal to the number of CPU cores, but is at least two.
         * Level of parallelism X guarantees that no more than X tasks can be executed in this dispatcher in parallel.
         */
        @JvmStatic
        public actual val Default: CoroutineDispatcher = createDefaultDispatcher()
    Could someone explain what I’m missing?
    j
    d
    • 3
    • 15
  • j

    JP

    03/16/2020, 12:31 PM
    This just came across my mind: Is there a tool to visualize the coroutine scope parent and child structure in the project?
    t
    • 2
    • 2
  • a

    Andrey Stepankov

    03/16/2020, 5:04 PM
    ReactiveX has a nice visualizations for describing operators called marble diagrams. I think kotlin flow needs them too. So I made this site, in Kotlin JS. https://flowmarbles.com/
    👍 4
    :kotlin: 2
    🔥 14
    👏 20
    🤔 2
    z
    l
    • 3
    • 7
  • j

    Jamie Taylor

    03/16/2020, 5:13 PM
    Is it safe to modify local mutable, non thread safe data structures in a coroutine that jumps between threads? e.g.
    fun main() = runBlocking<Unit> {
        val a = newSingleThreadContext("a")
        val b = newSingleThreadContext("b")
        launch {
            val set = mutableSetOf<Int>()
            repeat(100000) {
                withContext(a) {
                    set.add(it)
                }
                withContext(b) {
                    set.remove(it)
                }
            }
            println(set.size)
        }
    }
    I'd have thought it wouldn't be since set is being modified on multiple threads and isn't thread safe. On the other hand I can't see anything in the docs warning me not to do this and I haven't managed to produce any errors by doing seemingly unsafe operations.
    c
    a
    • 3
    • 8
  • s

    Steve

    03/16/2020, 6:19 PM
    I'm trying to test a suspend method which first tries to reach an API, but if that throws an exception, would fall back to a local method. However, it doesn't appear the catch in the suspend method is being executed
    s
    • 2
    • 7
  • m

    Manuel Vivo

    03/17/2020, 9:15 AM
    For people interested in what’s doing the Kotlin compiler under the hood 👌 Blog post about this coming along next week

    https://www.youtube.com/watch?v=IQf-vtIC-Uc&amp;list=PLWz5rJ2EKKc_T0fSZc9obnmnWcjvmJdw_&amp;index=5▾

    👍 8
    💪 1
    s
    j
    a
    • 4
    • 10
  • m

    myanmarking

    03/17/2020, 11:16 AM
    is there any flow operator that filters unique values ?
    d
    • 2
    • 4
  • m

    myanmarking

    03/17/2020, 1:07 PM
    public fun <T> Flow<T>.onEmpty(action: suspend FlowCollector<T>.() -> Unit): Flow<T> {
        var valueCount: Int = 0
        return flow {
            collect { valueCount += 1; emit(it) }
            if(valueCount == 0) action()
        }
    }
    does this makes sense in terms of implementation ?
    👍 1
    e
    • 2
    • 3
Powered by Linen
Title
m

myanmarking

03/17/2020, 1:07 PM
public fun <T> Flow<T>.onEmpty(action: suspend FlowCollector<T>.() -> Unit): Flow<T> {
    var valueCount: Int = 0
    return flow {
        collect { valueCount += 1; emit(it) }
        if(valueCount == 0) action()
    }
}
does this makes sense in terms of implementation ?
👍 1
e

elizarov

03/17/2020, 1:48 PM
Looks good to me
m

myanmarking

03/17/2020, 1:49 PM
will this work: flowOf<Int>().onEmpty{ emit(0) }. From my test it works, but someone mentioned it wont
e

elizarov

03/17/2020, 1:51 PM
It should work.
View count: 20