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

    oday

    11/15/2021, 1:18 PM
    I would like to turn this into a sequential call like with Rx’s
    andThen()
    viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
                petsRepository.getPets(this).collect { pets ->
                    deviceRepository.getDevices(this).collect { devices ->
    d
    r
    u
    • 4
    • 9
  • s

    SecretX

    11/15/2021, 2:38 PM
    is
    Job#invokeOnCompletion
    always invoked independent on the result of that Job (e.g. it gracefully completed, or it was cancelled while suspended)?
    j
    • 2
    • 1
  • a

    AmrJyniat

    11/15/2021, 3:44 PM
    Is there an equivalent to
    LiveData builder
    in flow?
    j
    a
    • 3
    • 2
  • d

    dimsuz

    11/16/2021, 11:39 AM
    Do I understand correctly that in this snippet flow2 will begin collection only after flow1 is finished (after approximately 3 sec)?
    val flow1 = flowOf { emit(1); delay(3000); emit(2) }
    launch {
      flow1.collect()
      flow2.collect()
    }
    j
    • 2
    • 2
  • j

    Justin Tullgren

    11/16/2021, 4:32 PM
    Hi, can anyone show me how to wait for a deferred with a timeout but allow the deferred to continue without a cancellation or timeout exception from the surrounding context?
    j
    • 2
    • 8
  • d

    dimsuz

    11/16/2021, 4:58 PM
    I want to have a
    supervisorScope
    in which I want to do mutliple
    launch
    -es and allow each one to fail individually without cancelling other running ones. At the same time I'd want to install an exception handler on the
    supervisorScope
    itself to centrally handle everyting. But it seems that this can't be done, according to official documentation, i'll need to do
    launch(handler)
    every time. Do I understand this right? It's not problematic, but I'd rather avoid "forgetting" to pass "handler" to
    launch
    and have it automatically provided...
    j
    c
    n
    • 4
    • 12
  • r

    Rak

    11/16/2021, 11:28 PM
    Hi, I am trying to call a suspend function from rxjava but I can’t seem to get it to work. I have imported
    rg.jetbrains.kotlinx:kotlinx-coroutines-rx2:1.5.2
    and tried to use GlobalScope.rxSingle but that method is not available on GlobalScope.
    n
    • 2
    • 1
  • r

    Richard Gomez

    11/17/2021, 1:19 AM
    What's the 'proper' way to bridge coroutines and a 3rd-party library (smallrye-mutiny)? I'd like to be able to do something like:
    @GET
    suspend fun get(): Uni<String> = uni { getFoo() } // run coroutine and return the result as a "Uni", which is similar to Reactor's Mono.
    The existing 3rd-party helpers in kotlinx.coroutines' rely on
    AbstractCoroutine
    , which warns that it shouldn't be used outside of the core lib. (e.g. mono builder)
    j
    y
    • 3
    • 14
  • u

    ursus

    11/17/2021, 2:07 AM
    I'd like to ask about scope cancelation. Is it 100% synchronous?
    someOtherPlace {
       someUserScope.launch {
           val userFlow: Flow<User?> = userDao.user()
           userFlow
            .collect {
                 // can 'it' be null here?
             }
       }
    }
    
    fun logout() {
    	allUserCoroutineScopes.forEach { it.cancel() }
    	userDao.deleteUser()
    }
    lets assume
    someUserScope
    is in the
    allUserCoroutineScopes
    list, and I'll only delete user after running the cancelation forEach Is there a way the flow at the top will emit null? Should never happen, right? Is it safe to
    !!
    there? (I'm looking at sources but its non obvious to me)
    a
    n
    • 3
    • 16
  • t

    tursunov abdulbois

    11/17/2021, 2:18 PM
    Hi, guys. I have AuthtenticationInterceptor to add token into header of request. In overrided intercept function it uses runBlocking builder to get token (token is obtained as flow object. Its repository implements PreferencesDataStore). I should replace runBlocking builder to other proper implementation. Because using runBlocking builder in production code is not good practice. Any sugestions?
    @Singleton
    class AuthenticationInterceptor @Inject constructor(profileRepository: ProfileRepository, @ApplicationScope coroutineScope: CoroutineScope) :
        Interceptor {
    
        private val tokenFlow: Flow<String?> = profileRepository.getProfileToken()
            .stateIn(coroutineScope, SharingStarted.Eagerly, null)
    
        override fun intercept(chain: Interceptor.Chain): Response {
            val requestBuilder = chain.request().newBuilder()
            val token: String? = runBlocking { // this line should be changed
                tokenFlow.firstOrNull()
            }
            token?.let { requestBuilder.addHeader("Authorization", it) }
            return chain.proceed(requestBuilder.build())
        }
    }
    j
    g
    • 3
    • 17
  • e

    elye

    11/18/2021, 4:06 AM
    Hi All, anyone know when I use coroutine on custom view onDraw (just for experiment purpose), it got drawn at weird coordinate?
    override fun onDraw(canvas: Canvas) {
            super.onDraw(canvas)
            CoroutineScope(Dispatchers.Default).launch { // <-- add coroutine
                canvas.drawLine(
                    0f, 0f,
                    width.toFloat(), height.toFloat(),
                    strokePaint
                )
            }
        }
    More detail (with image) here
    :not-kotlin: 1
    n
    • 2
    • 3
  • l

    loloof64

    11/18/2021, 12:28 PM
    Hi ! I'm using
    coroutineScope.launch {
    in order to start a coroutine in my code. But is there a variant of
    launch
    which runs the coroutine for a given amount of time, instead of infinitely ? Because otherwise, I'm afraid my code, which is a bit a kind of spaghetti as now, will be worse.
    b
    j
    j
    • 4
    • 4
  • r

    Roeniss Moon

    11/19/2021, 3:12 AM
    Just quick and broad question — would Virtual Thread change Coroutine implementation? Seems like VT would be GA in 3 years: https://openjdk.java.net/jeps/8277131
    a
    • 2
    • 2
  • c

    Colton Idle

    11/19/2021, 8:00 AM
    Still a flow/coroutine noob. I'm using firebase firestore and it has a listener approach to listen to updates on my data. I want to convert this into a Flowable so I can observe it. Is this an okay approach
    suspend fun getThingFlow(myId: String): Flow<Thing?> {
        val thingFlow = MutableStateFlow<Thing?>(null)
        FirebaseFirestore.getInstance()
            .document("things/$myId")
            .addSnapshotListener { value, error ->
                thingFlow.emit(value!!.toObject<Thing>())
            }
    
        return thingFlow
    }
    k
    t
    +2
    • 5
    • 30
  • h

    hfhbd

    11/19/2021, 10:34 AM
    With the new MM, will coroutines
    1.6.0
    support calling suspend functions (and flow collect) from other iOS threads?
    👀 8
    m
    • 2
    • 5
  • a

    Ayfri

    11/20/2021, 8:37 AM
    Hi, I still doesn't understand the basics of coroutines, like how to properly create some and launch them in a simple project, what are the dispatchers, how to launch multiple time a suspending function to optimise a big normal function etc Can someone explain me this examples please ?
    g
    j
    v
    • 4
    • 4
  • t

    Tolriq

    11/20/2021, 10:45 AM
    What is the proper way to listen to multiples flows of any possible type and have a resulting flow whose only purpose is to do something but does not care about the value, just that one of the flow have changed? Like I have 10
    flowX.drop(1)
    And would like to have a function that collect them all in a scope and call 1 function when any value is received (would be nice it the result was a flow so I can debounce too) So some kind of combine but without types and transform and supporting any number of input flows.
    j
    o
    o
    • 4
    • 10
  • v

    Vsevolod Tolstopyatov [JB]

    11/22/2021, 11:54 AM
    📣 📣 📣 kotlinx.coroutines 1.6.0-RC is here! Major highligths: • Completely reworked and now multiplatform kotlinx-coroutines-test module. • New API to manage dispatchers:
    limitedParallelism
    along with
    <http://Dispatchers.IO|Dispatchers.IO>
    being unbound for limited parallelism views. • K/N new memory model is now part of the release and all the coroutine primitives can be shared across multiple threads if the new memory model is enabled. • A lot of improvements and bug fixes. Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.6.0-RC
    ❤️ 8
    🎉 31
    🔥 12
    🙌🏼 2
    :kotlin-intensifies: 26
    🙌 8
    j
    b
    +4
    • 7
    • 21
  • t

    Thomas

    11/22/2021, 9:28 PM
    Will there be a
    native-mt
    release for
    1.6.0
    ?
    j
    i
    v
    • 4
    • 7
  • u

    ursus

    11/23/2021, 1:44 AM
    Is there a rxjava
    buffer
    equivalent in Flow? flow.buffer is not the same behavior from what I see, i.e. I want to collect upstream emits into some buffer, and only emit the buffer when its full/time elapses etc
    r
    g
    • 3
    • 5
  • u

    uli

    11/23/2021, 9:02 AM
    Hi there,
    limitedParallelism
    in 1.6.0 looks very promising. One question that jumped immediately to my mind: Is this feature recursive? i.e. let’s say I have 2 endpoints I want to serve and I want to limit thread usage to 64 overall, but only allow 50 threads per endpoint. Would the following code do that?
    val overallIODispatcher = Dispatchers.IO.limitedParallelism(64)
    val endpoint1Dispatcher = overallIODispatcher.limitedParallelism(50)
    val endpoint2Dispatcher = overallIODispatcher.limitedParallelism(50)
    b
    v
    • 3
    • 7
  • r

    rook

    11/24/2021, 3:20 PM
    I’m struggling to write tests around
    callbackFlow
    . I want to ensure that the value emitted from the flow matches the value that the callback receives. My problem appears to be that the
    ProducerScope
    block doesn’t get called until something subscribes to the flow. I thought that using
    shareIn
    would fix my problem, but it still doesn’t appear to kick off the
    ProducerScope
    in time
    fun someTest() = runBlocking {
      val expected = "someMessage"
    
      val resultFlow = getCallbackFlow().shareIn(this, SharingStarted.Eagerly, replay = 1)
    
      sendMessageToTriggerCallback(expected)
    
      val actual = resultFlow.first()
    
      assertEquals(expected, actual)
    }
    After adding some logging, I find that what happens is that first,
    sendMessageToTriggerCallback
    is invoked, then the callback is registered in the
    ProducerScope
    , then it suspends indefinitely awaiting the first signal from the
    resultFlow
    . I’ve tried a lot of variations on this pattern, and I can’t seem to make the
    ProducerScope
    run without blocking my ability to subsequently trigger sending the message. I’ve tried launching callback flow collection in its own job and sending the message a separate job and yielding between them. I’ve tried leveraging
    onSubscription
    , but that doesn’t fix the issue either, I get the same execution order as the example above. I’m at a bit of a loss as to how to enforce a deterministic execution order in this test case.
    j
    a
    • 3
    • 18
  • a

    Aaron Stacy

    11/24/2021, 11:12 PM
    Hi all, can anyone help me understand why this terminal collector does not seem to cancel the flow to which it's attached? https://pl.kotl.in/wB5Pt1jsQ
    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import java.util.concurrent.Executors
    
    
    fun main(args: Array<String>) = runBlocking {
        val requests = flow {
            var i = 0
            val serverDispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
            val handlerDispatcher = Executors.newFixedThreadPool(4).asCoroutineDispatcher()
            launch(serverDispatcher) {
                while (true) {
                    i += 1
                    val result = i
                    launch(handlerDispatcher) {
                        delay(500)
                        launch(serverDispatcher) {
                            emit(result)
                        }
                    }
                }
            }
        }
        
        // I want this to:
        //
        // 1. Suspend while collecting each emitted value.
        // 2. Continue to collect until seeing a value >= 4
        // 3. At that point continue.
        // 4. Cancel the flow (thereby closing the server's socket).
        //
        // But instead it suspends, the while loop keeps running and indicating it's emitting values, and the onEach print
        // statement never executes.
        requests.takeWhile { it < 4 }.onEach { println("got $it") }.collect()
    }
    a
    e
    • 3
    • 11
  • l

    lesincs

    11/25/2021, 12:22 AM
    Would a
    message
    posting by
    Dipatchers.Main
    already in
    message queue
    but not be picked by
    Looper
    will be removed from the
    message queue
    if the coroutine is canceled?
    z
    • 2
    • 1
  • t

    Tran Thang

    11/25/2021, 6:41 AM
    any one here can you explain to me what this code means?
    val coroutineContext: CoroutineContext get() = Job() + Dispatchers.Main
    w
    z
    • 3
    • 2
  • a

    Alexandru Hadăr

    11/25/2021, 3:19 PM
    👋🏻 Hey guys, question regarding testing the coroutines. Suppose I have a class like this:
    class Launcher(dispatcher: CoroutineDispatcher) {
        private val scope = CoroutineScope(SupervisorJob() + dispatcher)
        
        fun launchItem() {
            scope.launch { /* Do my thing here */ }
        }
    }
    I suppose the correct way to test this is to use
    Dispatchers.setMain(myDispatchers)
    in the
    @Before
    function and then use
    runBlocking
    in my test function, where I call
    launcher.launchItem
    , right? Or how should I test a method that’s not
    suspend
    but launches a
    coroutine
    inside ?
    j
    d
    • 3
    • 2
  • t

    Tgo1014

    11/26/2021, 9:18 AM
    Can someone help me understand about
    delay()
    s inside a
    runTest{}
    ? In my mind the delays would wait until I call
    advanceTimeBy()
    but in practice the test just run and ignore all the delays. What’s the point of the
    advanceTimeBy()
    then?
    u
    n
    u
    • 4
    • 29
  • k

    knthmn

    11/26/2021, 2:59 PM
    I have some Java api that looks like this
    interface Worker {
        // does the work, throws Exception promptly if cancel() is called
        fun doWork()  
        fun cancel()
    }
    What is the best way to convert it into
    suspend fun Worker.doWorkCancellable()
    ? Preferably something that works with a single threaded executor.
    j
    n
    • 3
    • 10
  • c

    Clament John

    11/27/2021, 10:09 AM
    I'm doing some reading on asynchronous programming in different languages. I'm adding what I learn into a WIP doc - you check it out here Q: Do you know of good blog posts or articles that explain how async is implemented in languages?
    l
    t
    e
    • 4
    • 19
  • d

    Dennis Schröder

    11/28/2021, 4:47 PM
    Is this in some way wrong or an appropriate attempt to set the cache to maxed?
    val sharedFlow = MutableSharedFlow<String> = MutableSharedFlow(replay = Int.MAX_VALUE)
    d
    j
    g
    • 4
    • 8
Powered by Linen
Title
d

Dennis Schröder

11/28/2021, 4:47 PM
Is this in some way wrong or an appropriate attempt to set the cache to maxed?
val sharedFlow = MutableSharedFlow<String> = MutableSharedFlow(replay = Int.MAX_VALUE)
d

Dominaezzz

11/28/2021, 4:55 PM
use case?
j

Joffrey

11/28/2021, 4:58 PM
If you need to replay every value ever emitted, maybe you should consider a cold flow instead? Where does the data of this flow come from?
g

gildor

11/29/2021, 4:37 AM
Looks like an easy way to get unexpected OOM
d

Dennis Schröder

11/29/2021, 8:11 AM
@Dominaezzz OK, let's assume your application uses event sourcing to persist data. On Startup we build a projection from all events and also want to push these events to a client via server sent events. So every time a client (subscriber) subscribes to the shared flow I want all events that we received before, be "replayed" for the client. Hope it makes sense?
g

gildor

11/29/2021, 8:23 AM
Should instead those events be persisted first and every client subscribe and request required amount of events when it’s needed from storage, not from mermory, instead persist all of them in memory and hope that it will be persisted by some code later and before OOM
j

Joffrey

11/29/2021, 8:25 AM
..or before a server restart
d

Dominaezzz

11/29/2021, 8:34 AM
Well, sure you can max out the cache (...ish, if there's no buffer space) but just beware of OOM as has been said above.
d

Dennis Schröder

11/29/2021, 11:43 AM
OK, but nothing special, besides OOM, which I already had in my mind as harmful! THX
View count: 4