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

    Ayfri

    07/16/2022, 4:18 PM
    Hi, is there a way to add an event listener to coroutine exceptions that we don't have access to ? So like if at any moment there is an exception in any coroutine the listener is run ?
    m
    • 2
    • 1
  • s

    Stephen Edwards

    07/18/2022, 5:54 PM
    In the
    kotlinx.coroutines.test
    migration guide for 1.6+ when talking about replacing
    runBlockingTest
    with
    runTest
    there is a little line:
    It works properly with other dispatchers and asynchronous completions.
    No action on your part is required, other than replacing runBlocking with runTest as well.
    What is meant by this? Why does
    runBlocking
    need to be replaced with
    runTest
    if there is no dispatcher/virtual time manipulation?
    d
    o
    • 3
    • 8
  • m

    myanmarking

    07/19/2022, 3:20 PM
    If i have three flows that return boolean, what is the best operator equivalent to this: (if(aaa || bbb || ccc) ?
    c
    r
    +3
    • 6
    • 37
  • k

    Kulwinder Singh

    07/20/2022, 6:20 AM
    class MyObject private constructor() {
        companion object {
            @Volatile
            private var INSTANCE: MyObject? = null
            
            fun isReadyInstance(): Boolean {
                return (INSTANCE != null)
            }
    
            fun getInstance(): MyObject {
                return INSTANCE  ?: throw Exception("Error Instance is not initialized.")
            }
    
            fun createInstance() {
                synchronized(this) {
                    if (INSTANCE == null) {
                        INSTANCE = MyObject()
                    }
                }
            }
    
            fun deleteInstance() {
                synchronized(this) {
                    INSTANCE = null
                }
            }
    }
    there is condition in my code to check for instance
    if (MyObject.isReadyInstance()) {
        MyObject.getInstance() //BUT HERE I GET -> "Error Instance is not initialized."
    }
    I think when
    isReadyInstance
    returned true meanwhile at some other place
    deleteInstance
    is called and therefore
    getInstance
    returned null, but how can i make sure that it won’t happen ?
    k
    a
    +2
    • 5
    • 7
  • m

    Matteo Mirk

    07/20/2022, 12:51 PM
    Hi everyone, in my team we’re having a hard time understanding if launching a coroutine in a certain point of the application is useful or not. We’re developing a gRPC service, and inside a global interceptor we need to publish a domain event, for tracking purposes. Since this action should be the “fire & forget” kind, we thought it would be a good idea to launch a coroutine for publishing the event and then carry on with the execution. Here’s a simplified version of our code with changed names:
    class PublishingServerCall<ReqT, RespT>(
            next: ServerCall<ReqT, RespT>,
            val publisher: EventPublisher
        ) : ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(next) {
            override fun close(status: Status, trailers: Metadata) {
                if (!status.isOk) {
                    runBlocking {
                        supervisorScope {
                            launch(Dispatchers.Unconfined) {
                                publisher.publishError(status)
                            }
                        }
                    }
                }
                super.close(status, trailers)
            }
        }
    I know there’s lot of grpc-specific stuff but bear with me, because it’s important details. Here is an implementation of a
    io.grpc.ServerCall
    , an abstraction needed by gRPC infrastructure to implement a custom interceptor. As you see we override the
    close()
    function because we’re interested in firing an event when the call is returning from a service and we have a response
    Status
    . We thought that this setup would allow us to publish the event asynchronously and move on in the interceptors chain without waiting for the publisher to complete. It seems to be working so far, but we only did some manual tests on our machines, it hasn’t been deployed yet. But the more I look at this code, the more I’m convinced it’s not doing what we thought: I have a feeling that the whole
    runBlocking {}
    part is useless and it’s blocking the thread anyway waiting for the return, and it would be the same to just invoke the publisher directly. Of course it’s needed because the enclosing function is not suspendable, but I’m full of doubts and don’t know if we wrote the right thing. Is this function blocking the request thread or is it returning right away, without waiting for the publication? Although skilled in service programming and Kotlin, we’re pretty much beginners on coroutines, so please if anyone has the expertise an advice will be much appreciated, thank you!
    j
    s
    • 3
    • 23
  • d

    Dean Djermanović

    07/21/2022, 1:22 PM
    Is there a way to collect each item in a separate coroutine in Kotlin Flow? For example, if I have this source:
    val source = flow {
            emit(1)
            delay(200)
            emit(2)
            delay(200)
            emit(3)
        }
    
    source
        .onEach { delay(500) }
        .collect {
            ...
        }
    I want my items to be collected after:
    1 - 500ms
    2 - 700ms
    3 - 900ms
    j
    n
    • 3
    • 4
  • s

    Slackbot

    07/21/2022, 1:28 PM
    This message was deleted.
  • g

    George

    07/22/2022, 1:15 PM
    Hi guys, i have a question. In case i have a shared flow and i want to apply filter, which is the simplest way to retrieve back the sharedFlow, since i cant just cast it back to SharedFlow as filer returns a Flow. Thanks in advance for any help
    t
    f
    • 3
    • 15
  • m

    Mark

    07/22/2022, 2:54 PM
    Is there something like
    Flow<T>.distinctUntilChanged(areEquivalent: (old: T, new: T) -> Boolean)
    but emits the newest of the equivalent values instead of the oldest?
    a
    s
    +3
    • 6
    • 11
  • l

    Lilly

    07/23/2022, 6:30 PM
    I would like to return a
    flow of T
    if cache is empty, otherwise T (as flow). I'm wondering which way is more appropriate:
    fun fetchStuff(): Flow<Stuff> = 
            if (cache.isNotEmpty()) {
                cache.asFlow()
            } else {
                api.fetchStuff()
            }.map { model -> model.toStuffModel() }
    
    or
    
    fun fetchStuff(): Flow<Stuff> = flow {
            if (cache.isNotEmpty()) {
                emit(cache.first())
            } else {
                emitAll(api.fetchStuff())
            }
        }.map { model -> model.toStuffModel() }
    r
    j
    • 3
    • 6
  • s

    Slackbot

    07/24/2022, 12:44 AM
    This message was deleted.
  • u

    ursus

    07/24/2022, 4:43 PM
    I'm trying to mimic CoroutineScope in Swift concurrency. My issue is that after I cancel the scope, it no longer accepts new `launch`es Which is good It does how ever still return a
    Job
    . What is this job? Is it already cancelled or what is it? Wouldn't be cleaner to throw?
    z
    • 2
    • 2
  • c

    Colton Idle

    07/25/2022, 6:45 AM
    Are there any Flow debugging tips or tools? For example, I think I have gotten myself into a bit of a mess with a few Flows that I'm using, and other flows that are collected as a result of one main flow (think Flow<UserSession> being collected and in collect{ someLongLastingFlowable() }) Is there like anyway to see how many flowsables I currently have going on? This would also be great when I put my android application into the background and hopefully I'd be able to inspect how many flowables haven't properly "shut down", or at this point should I just put log statement everywhere?
    👀 1
    d
    • 2
    • 2
  • l

    Lukas Lechner

    07/25/2022, 3:12 PM
    To the Android Developers: Flow VS LiveData What is the advantage of exposing Flows instead of LiveData from your ViewModel to your Views? One argument I keep hearing is that you can then use flow operators in your View. However, since Views should actually only render received states to the screen and not have actual logic in them, I don't see any use case where I would need a flow operator there... I asked this on twitter as well: https://twitter.com/LukasLechnerDev/status/1551584399485026307
    m
    a
    r
    • 4
    • 4
  • t

    tseisel

    07/26/2022, 6:52 PM
    It there a way to limit the rate at which a flow emits elements? My use case it to avoid running costly operations too often. For example, given the following source flow:
    val source = flow {
      emit("A")
      delay(100)
      emit("B")
      delay(50)
      emit("C")
      emit("D")
    }
    when applied a constraint of "max 1 element each 100ms", it should emit: • "A" at t = 0ms • "B" at t = 100ms • "D" at t = 200ms
    n
    r
    • 3
    • 4
  • f

    fitermay

    07/27/2022, 8:30 PM
    What's the pattern to dispose of a resource when a suspend function needs to allocated a disposable resource. How do I handle the case where the cancellation happens after the resource is allocated but right before it's returned?
    j
    z
    +2
    • 5
    • 51
  • f

    fitermay

    07/27/2022, 8:32 PM
    That is what if the cancellation happens when return is invoked
    j
    • 2
    • 1
  • l

    Lukas Lechner

    07/28/2022, 10:10 AM
    DataSources in Android Apps I have a datasource that exposes a
    SharedFlow
    and performs network request every minute while there are active subscribers and emits the result. I don't want to perform network requests when the app is in the background. Should it be the responsibility of the datasource to stop performing network requests when the app goes into background, or should it be the responsibility of the clients of the data source to cancel their coroutines that collect from the datasource? If it's the responsibility of the clients, then one faulty client implementation can make the datasource to stay active ....
    a
    • 2
    • 2
  • l

    Loney Chou

    07/28/2022, 3:31 PM
    What does
    resumes
    mean for continuations? Where and when the code after suspension point run? Like if the continuation runs in an infinite loop, does it mean that
    resumes
    will never end?
    e
    n
    • 3
    • 6
  • l

    Lucas

    08/02/2022, 1:27 AM
    I dont understand this. The warning says suspending fun has a CoroutineScope receiver, but the second class fails to find the "launch" method. Is this a bug or am i really misunderstanding this?
    t
    i
    +2
    • 5
    • 13
  • d

    deviant

    07/30/2022, 11:04 AM
    hey guys is it possible to use flows with the
    select
    builder? something like this
    flow {
     emit(select {
      someFlow1.onCollect()
      someFlow2.onCollect()
     })
    }
    n
    u
    g
    • 4
    • 5
  • d

    dimsuz

    08/02/2022, 1:29 PM
    Is it OK to share single instance of
    CoroutineExceptionHandler
    between several `CoroutineScope`s?
  • j

    Jesse Hill

    08/02/2022, 7:09 PM
    Is there a best practice for performing for handling a situation where you want to cancel/invalidate a flow if some input changes? The line of thought goes: 1. Get a flow representing the values for the term “a”. 2. Trigger a network call that results in updating the search with new results for “a”. 3. The collected flow now receives the updated data for the search “a”. 4. Start a new search for the term “abc”. 5. The previously collected flow is canceled and only the new flow with results for “abc” is collected. It works to hang onto the old Job where the initial flow is collected and then cancel that before collecting the new flow but that feels hacky. Playground Link (Code in the thread)
    g
    n
    • 3
    • 5
  • c

    Colton Idle

    08/03/2022, 3:37 PM
    I'm stress testing some callbackFlow code I have written. Here it is currently
    fun getBooks(): Flow<List<Book>> {
      return callbackFlow {
        val listener =
          FirebaseFirestore.getInstance()
            .collection("books")
            .addSnapshotListener { value, error ->
              if (error != null || value == null) { /*dosomething*/ }
              var books: List<Book>? = null
              runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
                  books = (value!!.toObjects())
              }
              trySend(books!!)
            }
        awaitClose { listener.remove() }
      }
    }
    this seems to work well... but to stress test it I wrapped
    books = (value!!.toObjects())
    with
    repeat (1000)
    and now my UI hangs. Shouldn't the dispatchers.io take care of this?
    runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
      repeat(1000) {
        books = (value!!.toObjects())
      }
    }
    u
    r
    +2
    • 5
    • 82
  • j

    Jan

    08/04/2022, 5:32 PM
    What could cause this exception? (thread)
    n
    • 2
    • 6
  • f

    Fudge

    08/05/2022, 6:55 AM
    I have some coroutine code that is getting cancelled with a
    JobCancellationException
    . How can I pinpoint the exact line of code that actually caused the coroutine to cancel? I've tried setting an exception breakpoint for
    JobCancellationException
    , but it doesn't get triggered for some reason.
    m
    u
    g
    • 4
    • 7
  • c

    Colton Idle

    08/07/2022, 1:21 AM
    This is potentially something that should just go into #getting-started but I'll just ask here. I have a list that I search through and while I search through it, sometimes the list is updated. No issues, except for that the list is large and so it's "slow" and lags the UI. I wrapped it in a
    withContext(Dispatchers.Default){
    but now I get a
    ConcurrentModificationException
    . I could understand if I was adding/removing to the list on Dispatchers.Default while main thread was swapping the list entirely... but I'm just searching via
    indexOfFirst
    . thoughts?
    e
    • 2
    • 62
  • c

    Colton Idle

    08/07/2022, 5:14 PM
    So I know coroutine cancellation is cooperative, but I have a fairly simple case here that I'm not sure how to dig myself out of. I essentially have a button that calls
    fetchMoreData()
    fun fetchMoreData(i) {
      viewModelScope.launch { ...
    but now if I call fetchMoreData() again, I actually want to cancel the old data fetching. How would I do that?
    e
    c
    f
    • 4
    • 13
  • j

    Juan Rada

    08/08/2022, 2:40 PM
    Hey folks I am trying to parallelize the processing of a flow. I am doing something like:
    private suspend fun process() = coroutineScope {    
        getFlow()
            .map { async(<http://Dispatchers.IO|Dispatchers.IO>) { ioBlockingFunction(it) } }
            .buffer(20)
            .map { it.await() }
            .collect()
    }
    my expectations is that 20 blocking operations will be trigger at time, then they will be awaited and then next 20 blocking operations will be trigger. What I am noticing is that somehow flow stop producing values and my app got block at flow element 25 of 30, or 100 (at a random point), even when flow function has more records to produce
    s
    • 2
    • 4
  • r

    Robert Williams

    08/08/2022, 4:27 PM
    I’ve just discovered that
    CoroutineDispatcher.dispatch
    method can be called directly in application code and this seems… problematic
    e
    z
    a
    • 4
    • 14
Powered by Linen
Title
r

Robert Williams

08/08/2022, 4:27 PM
I’ve just discovered that
CoroutineDispatcher.dispatch
method can be called directly in application code and this seems… problematic
For example I can easily write code that breaks structured concurrency as long as I have a Dispatcher:
dispatcher.dispatch(dispatcher) {
//some blocking code
}
and I can’t find much in the documentation or other sources that suggests we shouldn’t do this
So questions are: • Are there actually legitimate uses in application code (I guess it’s used internally but doesn’t seem like it should be public)? • Can it be hidden in public API? If not does it deserve a scary warning? • Is it actually better/ worse than using GlobalScope to do the same thing? That has lots of very scary warnings.
e

ephemient

08/08/2022, 4:52 PM
it has to be public to allow for custom and delegating dispatchers
it's not any more dangerous than
dispatcher.asExecutor().execute {
  //some blocking code
}
z

Zach Klippenstein (he/him) [MOD]

08/08/2022, 4:54 PM
It's very easy to write all kinds of code that doesn't use structured concurrency even without dropping to low-level apis like this.
r

Robert Williams

08/08/2022, 5:20 PM
You correctly mention it’s a low-level API so maybe the real problem is that it’s very common and recommended practice to pass into classes that need to do async work
I wonder if we lose anything else by using CoroutineContext instead when passing CoroutineDispatcher 🤔
Obviously wouldn’t stop you using eg Dispatcher.IO directly but it makes it harder to do wrong things and hides the low-level APIs which mostly aren’t needed
z

Zach Klippenstein (he/him) [MOD]

08/08/2022, 5:26 PM
It's generally better to accept a context vs a specific type of context element, since it is much more flexible
r

Robert Williams

08/08/2022, 5:32 PM
Yeah, I’ll try to do this going forward but doesn’t help that Google’s best practices use CoroutineDispatcher directly everywhere https://developer.android.com/kotlin/coroutines/coroutines-best-practices#inject-dispatchers
e

ephemient

08/08/2022, 5:35 PM
for dispatchers I don't think that's a good pattern anyway, since there's multiple you might want to inject (Default, IO) with the same type
if you use dagger, you'd need qualifiers to disambiguate them (which is doable, but annoying)
a

Adam Powell

08/08/2022, 7:18 PM
Fwiw we've been moving further away from that and back to
CoroutineContext
in more APIs
View count: 3