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

    Cody Mikol

    04/02/2021, 4:35 PM
    Does running a series of coroutine operations in a blocking context force all inner functionality to run synchronously? say you had something like
    runBlocking {
    
      val (foo,bar) = doAsync({ foo() },{ bar() })
      
      val (baz,bax) = doAsync({ baz(foo) },{ bax(bar) })
    
      return listOf(foo,bar,baz,bax)
    
    }
    Assuming doAsync runs the inner lambdas concurrently, would runBlocking the outer scope force these to run synchronously ?
    w
    v
    t
    • 4
    • 4
  • d

    Deepak Gahlot

    04/05/2021, 11:46 AM
    Hello All, I'm trying to build a Search functionality using BroadcastChannel api in Coroutine.
    d
    m
    • 3
    • 13
  • j

    Jiri Malina

    04/05/2021, 1:49 PM
    Hi there, how to add a timeout to
    awaitClose
    on
    CallbackFlow
    ? (details in thread)
    m
    b
    • 3
    • 7
  • v

    vkholyavin

    04/05/2021, 3:47 PM
    Hello. What is the best solution for replacing SingleLiveEvent with coroutines? Explanation: I have some events. And multiples subscribers for these events. But I need only one time to consume this event in any of the subscribers.
    c
    i
    c
    • 4
    • 3
  • v

    vineethraj49

    04/05/2021, 5:42 PM
    can someone please point to me in the kotlinx.coroutines codebase, where the logic is, that a Dispatchers.IO thread will continue on a Dispatchers.Default thread instead of spawning a new one?
    t
    k
    +3
    • 6
    • 18
  • s

    Spiral123

    04/05/2021, 9:30 PM
    stateflow
    😶 3
    🤤 1
    b
    h
    • 3
    • 2
  • b

    Big Chungus

    04/06/2021, 1:43 PM
    Why there are so many native targets that are mising coroutines-core artefacts? e.g. all linux targets except x64, watchosX64, mingwX86 & androidNdk
    o
    l
    +2
    • 5
    • 14
  • d

    Dariusz Kuc

    04/06/2021, 2:10 PM
    Hello 👋 Was just wondering about Flow and context (https://kotlinlang.org/docs/flow.html#flow-context). I understand that we should not be emitting new values from new coroutines but is it fine to start coroutines to fetch some data or that should still fall under
    channelFlow
    ? e.g.
    flowOf(1, 2, 3).map { 
      id -> coroutineScope {
        val first = async { retrieve(id) }
        val second = async { retrieveOther(id) }
        first.await() + second.await()
      }
    }
    l
    • 2
    • 5
  • k

    knthmn

    04/07/2021, 3:31 AM
    I want to unit test an interface like this
    interface Foo {
        fun flowValue(): Flow<Value>  // flow the stored value
        suspend fun setValue(value: Value)  // update the stored value
    }
    however the implementation is not for me to control, and sometimes
    flowValue()
    sometimes emit the old value several times before emitting the set value. What is the best way to test this?
    l
    u
    • 3
    • 7
  • d

    darkmoon_uk

    04/07/2021, 8:35 AM
    Sometimes there are valid reasons that part of a Reactive System (
    Flow
    setup) forms a circular reference. In these cases, it's impossible to declare all parts of an overall Flow linearly; at some point we need to reference a part that hasn't been declared yet. In RxJava the idiomatic way to work around this was using
    Relay
    - a specialised
    Subject
    . Is there a
    Flow
    equivalent? It seems that a
    MutableSharedFlow
    with
    replay = 0
    will have the right semantics.
    e
    • 2
    • 2
  • n

    niqo01

    04/08/2021, 3:06 AM
    Is there a way to use
    retry
    based on a valid emitted value and not based on exception occuring? My emitted value looks like this
    public sealed class BillingClientState{
            public object Initializing: BillingClientState()
            public data class Available(val client: BillingClient): BillingClientState()
            public object Unavailable: BillingClientState()
            public object Disconnected: BillingClientState()
        }
    I want rety when Disconnected is triggered
    e
    a
    • 3
    • 7
  • t

    tkez

    04/08/2021, 11:08 AM
    Some basic question about coroutine in android. Can I assume that we should always use viewmodelScope, which associated with lifecycle whenever possible. But in some occasion, we might not have those scope, for eg. in service or receiver. In that case, is it advisable to define job and scope within, or use Globalscope?
    private val job = SupervisorJob()
    private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + job)
    d
    a
    • 3
    • 11
  • s

    Simon Lin

    04/09/2021, 2:13 AM
    Do you have any sample code/project that using coroutines in the android custom view? I would like to learn the best practice that handle coroutines in custom view.
    m
    s
    g
    • 4
    • 6
  • n

    Nikola Milovic

    04/09/2021, 9:01 AM
    Hey guys, where can I read more about this kind of behaviour?
    fun A() {
    B()
    C()
    }
    
    fun B(){
      scope.launch{
      //call some suspending fun
       }
    }
    So now C will be executed before B finishes even tho B isn't suspending fun?
    m
    u
    • 3
    • 11
  • g

    genovich

    04/10/2021, 5:25 PM
    Hi everyone 👋 Can anybody explain me what happens with second
    Deferred
    in
    select
    when the first one returns value?
    select {
       deferred1.onAwait { it }
       deferred2.onAwait { it }
    }
    e
    • 2
    • 8
  • n

    natario1

    04/11/2021, 10:47 AM
    Is it possible to have something like
    SharingStarted.WhileSubscribed()
    with the extra feature that if the flow has never emitted, wait for first emission before stopping? In other words, if someone subscribes but then leaves before receiving the first value, wait for it before stop. Looking at source code it seems quite easy to modify
    WhileSubscribed
    to do this (just add sharedFlow.first()). But we don't have the SharedFlow when creating
    SharingStarted
    , we only have the upstream flow which means that values in the replay cache are ignored.
    d
    • 2
    • 3
  • n

    Nate Emmons

    04/12/2021, 2:27 AM
    (Please redirect me if this should be in #getting-started). I'm jumping in way over my head and trying to do a multiplayer game server for my first Kotlin project. I'm trying to use Ktor Websockets for client-server communication. It's my understanding that i can run the 'core game loop' as a separate coroutine and then communicate with the client websocket coroutines via channels, am i going in the right direction? My game loop does not need to be very fast at all so i'm assuming i can comfortably
    delay
    back to the client websocket coroutines relatively frequently to look for new input
    b
    • 2
    • 3
  • n

    natario1

    04/12/2021, 10:34 AM
    How would you go to debug why a coroutine is being canceled? Working on Android AFAIK we can't use
    kotlinx.coroutines.debug
    and the debugger in Android Studio has no "Coroutines" tab.
    t
    e
    • 3
    • 2
  • d

    Daniele B

    04/12/2021, 12:58 PM
    I am manually creating “scope1” and “scope2", with “Job()” and the same coroutine name.
    val scope1 = CoroutineScope(Job() + "myscope")
    val job1 = scope1.launch { … }
    
    val scope2 = CoroutineScope(Job() + "myscope")
    val job2 = scope2.launch { … }
    Are “scope1" and “scope2” actually the same scope, or are they different?
    e
    • 2
    • 1
  • j

    Jrichards1408

    04/12/2021, 1:29 PM
    hi, how do you evaluate an expression that calls a suspense function? i get an error saying suspense function is not supported in evaluation
    l
    d
    j
    • 4
    • 6
  • v

    vineethraj49

    04/13/2021, 3:37 AM
    is there a way to force
    withContext(<http://Dispatchers.IO|Dispatchers.IO>)
    onto a new thread? applies to
    GlobalScope.future(<http://Dispatchers.IO|Dispatchers.IO>)
    etc as well
    z
    r
    e
    • 4
    • 7
  • u

    uli

    04/13/2021, 3:39 PM
    Hi all, is it a bug that suspendability on a receiver lambda has to be explicitly declared? If I have
    private suspend fun <T> (suspend () -> T).foo()
    and
    private suspend fun <T> bar(lambda: suspend () -> T)
    I need to explicitly write
    suspend { delay(1)  }.foo()
    but it’s fine to just call
    bar { delay(1) }
    without suspend keyword
    d
    • 2
    • 5
  • r

    rook

    04/13/2021, 4:19 PM
    I’m noticing a little bit of inconsistent behavior with
    invokeOnCompletion
    . Given the following
    launch(Dispatchers.Default) {
      val theJob = async(<http://Dispatchers.IO|Dispatchers.IO>) {}
    
      // do some work
    
      theJob.invokeOnCompletion { println() }
    }
    If
    do some work
    takes longer than
    theJob
    to complete, the handler block runs on
    Dispatchers.Default
    , whereas if
    theJob
    takes longer than
    do some work
    , the handler block runs on
    <http://Dispatchers.IO|Dispatchers.IO>
    .
    d
    • 2
    • 2
  • s

    Steffen Funke

    04/14/2021, 8:40 AM
    Hey all, in RxJava, we have 
    doOnNext
     operators for side-effects, like printing, etc. What is the equivalent in Kotlin Flows? AFAIK, 
    onEach
     consumes the flow, and would not be appropriate there. Or am I missing something?
    w
    e
    • 3
    • 7
  • p

    Peter

    04/14/2021, 7:15 PM
    i’m wondering why
    CancellableContinuationImpl
    would have such a large retained size?
    • 1
    • 4
  • s

    spand

    04/15/2021, 6:19 AM
    Today I needed this:
    class SuspendAtomicRef<T : Any> {
        private var data: T? = null
        private val mutex = Mutex()
    
        suspend fun getOrSet(init: suspend () -> T): T {
            return mutex.withLock {
                data ?: init().also { data = it }
            }
        }
    }
    Seems pretty basic so I wonder if I am missing it in the coroutines library?
    d
    e
    • 3
    • 7
  • c

    Chris Grigg

    04/15/2021, 1:56 PM
    Hey everyone, just trying to confirm something here. If I call 
    collect
     on a SharedFlow and then call 
    delay
     within the collect’s body, will it block other subscribers from retrieving emitted messages? My expectation is that it will because my understanding of flows is that they distribute messages synchronously through subscribers.
    e
    • 2
    • 2
  • a

    Andrew Ebling

    04/15/2021, 3:40 PM
    When using
    suspend
    functions in Android (which get triggered from non-UI events) and you suddenly find you need a
    Context
    to get something done (in this instance load a preference value), what are sound approaches to adopt? I understand that storing
    Context
    references is a no-no, due to the potential to leak Activites.
    a
    z
    • 3
    • 5
  • b

    bod

    04/15/2021, 7:51 PM
    Hello, World! It's a small thing, but I noticed that when I have a simple program with a
    suspend fun main()
    , the program doesn't exit at the end of the
    main
    . It's not big deal since I can of course manually end it with
    exitProcess(0)
    but I'm wondering if I'm doing something wrong, or is this normal?
    l
    u
    • 3
    • 6
  • r

    rocketraman

    04/17/2021, 12:35 AM
    How would you create a flow that emits values when they change and periodically emits the last value available, every x duration since the last change or emit? So far what I've got is this:
    flow.transformLatest { value ->
      while(currentCoroutineContext().isActive) {
        emit(value)
        delay(x)
      }
    }
    s
    o
    • 3
    • 7
Powered by Linen
Title
r

rocketraman

04/17/2021, 12:35 AM
How would you create a flow that emits values when they change and periodically emits the last value available, every x duration since the last change or emit? So far what I've got is this:
flow.transformLatest { value ->
  while(currentCoroutineContext().isActive) {
    emit(value)
    delay(x)
  }
}
s

Steffen Funke

04/17/2021, 7:35 AM
A probably naive approach: I'd
combine
a timer (for the "periodical every x seconds part"), and my actual flow, like this:
// the timer
val timer = (0..Int.MAX_VALUE).asSequence().asFlow().onEach { delay(1_000) }

// your other flow
val other = flow {
    emit("A")
    delay(1500L)
    emit("B")
    delay(1500L)
    emit("C")
}

// combine them
launch {
    combine(timer, other, ::Pair)
        .collect { (timer, other) ->
            println("bling: ${timer} | ${other}")
        }
}
Of course you can ignore / map away the received timer value, since you are probably only interested in the actual value.
r

rocketraman

04/17/2021, 5:54 PM
Interesting approach, thanks. The transformLatest seems to encapsulate the logic a bit better though.
o

okarm

04/20/2021, 10:53 PM
My first instinct would be to employ a channelFlow and upon receiving an upstream value 1. Emit the value 2. Spin up a repeating coroutine to periodically emit this value into the channel again.
r

rocketraman

04/20/2021, 10:55 PM
3. Cancel all of the repeating coroutines once a new value is received.
What does it get me over the
transformLatest
approach?
o

okarm

04/20/2021, 11:08 PM
Likely nothing
View count: 2