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

    natario1

    04/29/2021, 11:32 AM
    Is there an easy way to await the first result of two Deferred and cancel the other?
    d
    c
    +1
    8 replies · 4 participants
  • n

    natario1

    04/29/2021, 4:09 PM
    How do you make a long running, blocking function cancellable? E.g. with this third-party class:
    class Worker {
      fun doWork()
      fun cancelWork()
    }
    My attempt below (untested) doesn't look very good, I wonder if there's any better way.
    coroutineScope {
      val job = launch {
        while (isActive) {
          delay(50)
        }
      }
      job.invokeOnCompletion { 
        if (it is CancellationException) {
          worker.cancelWork()
        }
      }
      worker.doWork()
      job.cancel()
    }
    a
    3 replies · 2 participants
  • u

    ursus

    04/30/2021, 12:50 AM
    How do you folks architect around the fact that shared flows (correctly) need scope as a parameter?. Should only classes that own their scope use sharing operators? In rx I used to do this
    class AppInForeground {
    	val appInForeground: Observable<Boolean> by lazy {
    		Lifecycle.wrapAsObservable()
    		   .distinctUntilChanged()
    		   .publish()
    		   .replay(1)
    	}
    }
    naive Flow implementation
    class AppInForeground {
    	fun appInForeground(scope: CoroutineScope) {
    		if (_appInForeground == null) {
    			synchornized(this) {
    				if(_appInForeground == null) {
    					_appInForeground = Lifecycle.wrapAsFlow()
    						.distinctUntilChanged()
    						.shareIn(scope, SharingStarted.Lazily, 1)
    				}
    
    			}
    		}
    		return _appInForeground!!
    	}
    }
    just looks stupid, however the main issue is that callers should not determine the scope, right? I think idiomatic way is this
    class AppInForeground : HasLifecycle {
    	private val scope = SupervisorScope(..)
    
    	private val _appInForeground = MutableStateFlow(false)
    	val appInForeground: Flow<Boolean> get() = _appInForeground
    
    	override fun create() {
    		scope.launch {
    			Lifecycle.wrapAsFlow()
    				.distinctUntilChanged()
    				.collect {
    					_appInForeground.value = it
    				}
    		}
    	}
    
    	override fun destroy() {
    		scope.cancel()
    	}
    }
    Works, however its a bit less efficient, i.e. it subscribers when the AppInForeground class si instantiated, also whole lot more ceremony... Is there a way more close to the rx way? or should I just deal with it?
    u
    2 replies · 2 participants
  • c

    Cody Mikol

    04/30/2021, 2:08 PM
    Does hibernate work alongside coroutines?
    c
    1 reply · 2 participants
  • m

    mkrussel

    04/30/2021, 3:01 PM
    I'm trying to create a cold
    Flow
    where a lot of updates can happen at once and I want the collector to only process the last one. The producer and the consumer are both on the UI thread. The desired behavior is when the producer gets out of their loop and goes back to waiting for some event, then the consumer gets the latest state. What I have now is a
    callbackFlow
    that is
    conflated
    .
    val flow = callbackFlow<Any> {
        event.register { offer(someValue) }
        awaitClose { event.unregister() }
    }.conflate()
    val job = scope.launch() {
       flow.collect { }
    The scope is using Android's
    MainScope
    . And the event is sending events on the main thread. When I was using a
    MutableStateFlow
    this behaves as I wanted, but with the conflated
    callbackFlow
    the caller is getting the first and last event, once all the events have been offerred.
    b
    o
    6 replies · 3 participants
  • t

    T

    05/01/2021, 12:09 PM
    Hello, I'm trying to solve the following problem: Multiple Coroutines (on different threads) may send a request to an API. The API may respond, that a login is required. In this case the first coroutine should initiate the login sequence. All other coroutines should suspend until the sequence is executed. I currently implemented this as follows:
    val loginSequence = SharedMethod<String>()
    
    suspend fun request() {
        try {
            loginSequence
                .awaitIfNeeded()
    
            return doRequest(...)
        } catch(e: LoginRequiredException) {
            return loginSequence.awaitOrBlock(
                onBlockReturn = {
                    return@awaitOrBlock executeLoginSequence(e)
                },
                onAwaitReturn = {
                    return@awaitOrBlock doRequest(
                        ...
                    )
                })
        }
    }
    with the implementation of this class with mutexes:
    class SharedMethod<T> {
        private val mutex: Mutex = Mutex()
    
        suspend fun awaitOrBlock(
            onBlockReturn: suspend () -> T,
            onAwaitReturn: suspend () -> T
        ): T = coroutineScope {
            val isLocked = mutex.tryLock()
    
            if (!isLocked) {
                awaitIfNeeded()
    
                return@coroutineScope onAwaitReturn()
            }
    
            try {
                return@coroutineScope onBlockReturn()
            } finally {
                mutex.unlock()
            }
        }
    
        suspend fun awaitIfNeeded() {
            while (mutex.isLocked) {
                delay(1000)
            }
        }
    }
    Is there a better way to implement this behaviour? Especially the "while (mutex.isLocked) {...}" seems pretty ugly. Is this the right place for using mutexes? Happy to hear your thoughts. :)
    d
    2 replies · 2 participants
  • m

    Marcin Wisniowski

    05/02/2021, 3:52 PM
    How do I get usable stack traces for exceptions in coroutines? I'm using a crash reporting service, but all the exceptions I'm getting lose all context, since they only have the function the exception happened in, and that's it, since the next element of the stack trace is
    BaseContinuationImpl.resumeWith
    and the rest of coroutines machinery, not the "actual" calling method.
    l
    u
    3 replies · 3 participants
  • a

    Andrew Gazelka

    05/02/2021, 8:57 PM
    Is there a way to get the job a SharedFlow is launched in? Basically, I want to do something like this
    // a method ...
    val (sharedFlow, job) =  flow.shareIn(scope, SharingStarted.Eagerly)
    jobs.add(job)
    return sharedFlow
    d
    6 replies · 2 participants
  • b

    Brian Dilley

    05/02/2021, 9:23 PM
    Given a collection of
    Deferred<X>
    - what’s the best way to retrieve their results as they come in - and at any point bail after receiving a result that you’re looking for while canceling the others?
    a
    e
    4 replies · 3 participants
  • u

    ursus

    05/03/2021, 2:24 AM
    Hi, I need to insert a initial value to a stream that sometimes doesn't emit, however if it emits within a window of time, take the real value, not the manual initial one TLDR; debounce first value - I have this
    private fun <T> Flow<T>.onStartDebounced(initialValue: T, debounceMillis: Long): Flow<T> {
        return onStart { emit(initialValue) }
            .withIndex()
            .debounce { if (it.index == 0) debounceMillis else 0L }
            .map { it.value }
    }
    Works, but im a Rx guy, is there something more idiomatic / performant (so I can actually learn something)?
    b
    e
    12 replies · 3 participants
  • m

    Mark

    05/03/2021, 3:53 AM
    What is the standard way to refactor a lazy property to a suspend function that uses a cached value on subsequent runs?
    CompletableDeferred
    or something else?
    // from this
    val someProperty: Int by lazy {
        // refactoring to perform some suspendable logic
    }
    
    // to this
    suspend fun someProperty(): Int {
        // only should be executed max once (and then cached)
    }
    e
    o
    15 replies · 3 participants
  • j

    julioromano

    05/03/2021, 1:36 PM
    Is there a way to keep track of the children Jobs launched within a given
    CoroutineScope
    ? As if the
    CoroutineScope
    were a message queue and Jobs were messages in it: Would there be a way to track if the
    CoroutineScope
    is currently handling Jobs or is sitting idle? What I’m trying to accomplish: I’d like to build an idle/busy signal (possibly as a
    Flow<Boolean>
    ) that will tell me whether a
    CoroutineScope
    is currently running any coroutines or not.
    e
    l
    +1
    16 replies · 4 participants
  • e

    Erik

    05/03/2021, 1:50 PM
    MutableSharedFlow()
    by default has no buffer (
    replay = 0
    ,
    extraBufferCapacity = 0
    , i.e.
    buffer = replay + extraBufferCapacity = 0
    ). Does that mean that if I have many emitters that call
    emit
    , that they would suspend (in order) until the subscribers of the shared flow process the emissions one by one? So, in other words: has the buffer moved away from the shared flow, that intrinsically has no buffer space, to the coroutine scope(s) that now contain various suspended child coroutines trying to
    emit
    ?
    t
    f
    36 replies · 3 participants
  • c

    Chris Grigg

    05/03/2021, 2:59 PM
    Hi everyone, I wonder if someone could clarify something for me. When I first learned about coroutines, I remember being taught that one should prefer to use
    launch
    from your existing context and then move it elsewhere using
    withContext
    instead of calling
    launch
    and specifying dispatcher.
    scope.launch { withContext(<http://Dispatchers.IO|Dispatchers.IO>) { work() } }
    instead of
    scope.launch(<http://Dispatchers.IO|Dispatchers.IO>) { work() }
    . I remember this being described as preferential since there was some performance penalty when launching in a different context that did not occur when moving a running coroutine using
    withContext
    . I’m trying to find guidance on this again and I can’t find anything about it. Did I misunderstand something when I was first learning?
    z
    f
    +1
    5 replies · 4 participants
  • e

    Erik

    05/03/2021, 3:15 PM
    About this documentation: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-mutable-shared-flow/emit.html If you call
    MutableSharedFlow<Int>().emit(0)
    (from a suspending function), then the
    emit
    call does not suspend. The documentation says that on buffer overflow the call should suspend. To me it seems that there is no buffer, so
    emit(0)
    causes a buffer overflow, so the
    emit
    call should suspend. Instead, it returns quickly! Am I misinterpreting the following?
    suspending on buffer overflow
    Or can the documentation be improved?
    4 replies · 1 participant
  • k

    Kshitij Patil

    05/03/2021, 3:32 PM
    How to test
    MutableSharedFlow
    with
    replay=0
    ? I'm using turbine for testing Kotlin Flows and I managed to write tests for
    MutableStateFlow
    , but the same emitted values doesn't work for SharedFlows.
    TestFlows.kt
    e
    u
    19 replies · 3 participants
  • e

    ermac10k

    05/06/2021, 11:59 AM
    Hello there! I made some measures and coroutines loose to parallelStream when they deal with parallel processing of collection elements. It’s sad 😔 Kotlin v1.3.72
    ❓ 3
    g
    e
    55 replies · 3 participants
  • p

    Pablo

    05/06/2021, 2:08 PM
    How can I create a timer? I've done it like this
    scope.launch{
     var foo = true
     while(foo){
     delay(1_000)
         //do some actions here
         //with these actions I check if the time is correct and if goes inside the if i put the foo to false so it leaves the while
         if(whatever) {
           foo=false
           //call one method here
         }
     }
    }
    Is this a correct way? Is there a better way with flow?
    d
    g
    +1
    8 replies · 4 participants
  • p

    Pablo

    05/06/2021, 2:31 PM
    I found this :
    val timer = (0..MyInterval) 
     .asSequence()
     .asFlow()
     .onEach { delay(1_000) }
    
    timer.collect { //do something }
    But how do I stop the timer as I do with if(whatever) foo = false?
    g
    n
    2 replies · 3 participants
  • r

    Rob

    05/06/2021, 6:15 PM
    I'm looking for a way to update a UI from a flow at a given interval. I was using sample() which works but the first emit is delayed. Is there a way to emit the first item without delay using sample() or some other function?
    Untitled.kt
    g
    1 reply · 2 participants
  • b

    Ben

    05/06/2021, 7:38 PM
    I'm looking to re-emit the last search result when refresh() is called. What I have below works, but is there a nicer way of doing it? (More specifically, I found the apply block for the refreshChannel was necessary for the resultStream to emit at all, but it doesn't feel right).
    private val searchQueryStream = MutableStateFlow<String>("")
    
    private val refreshChannel = Channel<Unit>(Channel.CONFLATED).apply { offer(Unit) }
    
    val resultStream: Flow<PagingData<TenorGifTileData>> =
        searchQueryStream
            .combine(refreshChannel.receiveAsFlow()) { queryStream, _ -> queryStream }
            .filter { searchQuery ->
                searchQuery.query.isNotEmpty()
            }
            .flatMapLatest { searchQuery ->
                repository.resultsForSearchQuery(searchQuery)
            }
    
    fun refresh() {
        if (!refreshChannel.isClosedForSend) {
            refreshChannel.offer(Unit)
        }
    }
    u
    1 reply · 2 participants
  • u

    ursus

    05/07/2021, 11:50 AM
    you make suspending what you want to be cancelable marking blocking code thats not cancelable with suspend does nothing however if you mark it suspend, then by convention it should be main-safe, so yea apply dispatcher then
    u
    1 reply · 2 participants
  • m

    mbonnin

    05/07/2021, 3:07 PM
    How can I make sure to start collecting to a
    MutableSharedFlow
    before emitting something ?
    val mutableFlow = MutableSharedFlow<Int>()
          val sharedFlow = mutableFlow.asSharedFlow()
    
          // start listening to the sharedFlow
          launch {
            sharedFlow
                .collect {
                  // by the time we start collecting, the first item is gone already
                  // and nothing is received
                  println("$it")
                }
          }
          // emit something 
          mutableFlow.emit(1)
    Adding a delay before emitting works but doesn't sound great and I don't see a way to enforce a before-after relationship there
    t
    j
    +1
    12 replies · 4 participants
  • a

    ArcticLampyrid

    05/08/2021, 8:48 AM
    Hi, is there any plan to release v1.5.0(stable)? Kotlin v1.5 has been released, and the coroutines library is the only thing that blocks me from updating now.
    ➕ 1
    d
    e
    +1
    5 replies · 4 participants
  • t

    theapache64

    05/09/2021, 9:30 AM
    [RESOLVED] What's the difference between casting to
    StateFlow
    vs
    asStateFlow
    ? 🧵
    d
    j
    +1
    6 replies · 4 participants
  • m

    Marian Schubert

    05/09/2021, 9:51 AM
    is it possible to complete MutableStateFlow? I just started playing with coroutines / flow so I'm not really sure whether it's even meaningful question to ask 🙂
    a
    2 replies · 2 participants
  • y

    Yan Pujante

    05/10/2021, 1:19 PM
    I am a bit new to coroutines/flow and wondering if this is a good design or not. I have a server that can receive long running job to process. Each job must be run sequentially. So I have something like this:
    class JobsMgr {
        private val _jobsToProcess = Channel<Job>(Channel.UNLIMITED)
        private val _jobsProcessed: Flow<Job> = _jobsToProcess.consumeAsFlow().map { job -> /* processing */ }.flowOn(Dispatchers.Default)
    
      init {
           // I find this very ugly.. is there a better way?
            Executors.newSingleThreadExecutor().execute {
                runBlocking {
                    _jobsProcessed.collect {
                        delay(10 * 1000)
                        _lock.withLock { _jobs.remove(it.jobId) }
                    }
                }
            }
      }
    
    fun enqueueJob(...) { 
    //...
                   runBlocking {
                    _jobsToProcess.send(job)
                }
    }
    
    }
    It is running in a spring boot application so I do not have control over the main loop. This is why I created a process to collect and remove the completed jobs. Is this how Channel/Flow is supposed to be used? And is there a better way to "start" the collection. That seems like ugly code to me but not sure how to do better.
    m
    u
    12 replies · 3 participants
  • c

    carbaj0

    05/11/2021, 4:42 PM
    Hi! I see this piece of code in a library. is the function
    suspendCancellableCoroutine <Nothing> {}
    needed ? For me is just an empty call
    class ProduceStateScopeImpl<T>(
        state: MutableState<T>,
        override val coroutineContext: CoroutineContext
    ) : ProduceStateScope<T>, MutableState<T> by state {
    
        override suspend fun awaitDispose(onDispose: () -> Unit): Nothing {
            try {
                suspendCancellableCoroutine<Nothing> { }
            } finally {
                onDispose()
            }
        }
    }
    s
    l
    3 replies · 3 participants
  • f

    frankelot

    05/12/2021, 1:55 PM
    Hi All! 👋 I'm wondering if this is OK
    a
    l
    +2
    75 replies · 5 participants
  • t

    taer

    05/12/2021, 2:44 PM
    Once upon a time long long ago, someone "translated" a flow/map/collect call into the "imperative" code that is running. Basically showing how the emit(FOO) is the one actually calling the collect lambda through all the chain. I can't find. It was really helpful for me, and now I'd like to help my co-worker. I don't know if this wonderful person did it manually, or there's a way to generate. If that makes sense, can you help do it again? 🙂
    c
    3 replies · 2 participants
Powered by Linen
Title
t

taer

05/12/2021, 2:44 PM
Once upon a time long long ago, someone "translated" a flow/map/collect call into the "imperative" code that is running. Basically showing how the emit(FOO) is the one actually calling the collect lambda through all the chain. I can't find. It was really helpful for me, and now I'd like to help my co-worker. I don't know if this wonderful person did it manually, or there's a way to generate. If that makes sense, can you help do it again? 🙂
suspend fun foo(){
       flow { emit(1)  }
            .map { it*2 }
            .collect { println(it) }
    }
c

Casey Brooks

05/12/2021, 3:14 PM
This presentation from KotlinConf might be what you’re thinking of

https://www.youtube.com/watch?v=tYcqn48SMT8▾

t

taer

05/12/2021, 3:26 PM
very close.. Thanks!
View count: 10