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

    Mayur

    02/25/2021, 10:09 AM
    Need Help - Android App - Coroutines background: Create secure socket server to allow maximum possible socket client to connect. as to build connection with socket client, socket server need continues loop to accept connection. along way to communicate with each client need to open stream input and output to listen and send messages, this also need continues loop to read messages. Technically: I have tried using Thread but at this level handle thread and expect performance is hard, so come to the solution to use Coroutine. I have also tried Ktor for coroutine socket but don't find proper way(or I don't understand) how we want to build SSL Not a Coroutine master just learn and implemented. Problem: observed its uses higher CPU after some sort of time and UI start freezing, sometimes it hanging the phone. Also, continuously getting below kind of warning logs:
    zygote: Explicit concurrent copying GC freed 35008(4MB) AllocSpace objects, 5(164KB) LOS objects, 89% free, 2MB/20MB, paused 211us total 67.413ms
    
    zygote: Increasing code cache capacity to 512KB
    
    Choreographer: Skipped 48 frames!  The application may be doing too much work on its main thread.
    
    zygote: Do partial code cache collection, code=53KB, data=54KB
    zygote: After code cache collection, code=53KB, data=54KB
    zygote: Increasing code cache capacity to 256KB
    (after some optimization it lowered but still having the issue) I need help to select the right approach understand the issue insightful in way to resolve and use correctly.
    n
    • 2
    • 2
  • r

    ribesg

    02/25/2021, 10:10 AM
    I have a custom scope built like this
    CoroutineScope(Dispatchers.Default + CoroutineExceptionHandler { _, e ->
                        log.error("Uncaught error in scope", e)
                    })
    But it looks like when an error occurs, or rather after a few errors, coroutines basically stop like if the scope was dead or something. Eveyrthing seems stuck. Does calling the CoroutineExceptionHandler cancel the scope’s job or something? Do I need to specify a
    + SupervisorJob()
    when building the scope? I don’t really understand what’s happening
    k
    l
    • 3
    • 3
  • d

    dan.the.man

    02/25/2021, 8:16 PM
    If I want to replace livedata with StateFlow, should I be using
    collect
    or
    onEach
    to subscribe to the updates on Stateflow
    p
    w
    z
    • 4
    • 5
  • s

    SecretX

    02/26/2021, 6:55 AM
    open class Listener<T>(element: T) {
    var value: T = element
    protected set(value) {
    field = value
    notifyObservers(field)
    }
    private val observers: ConcurrentHashMap<UUID, Observer<T>> = ConcurrentHashMap()
    private fun notifyObservers(newValue: T) {
    observers.forEach { it.value.onChange(newValue) }
    }
    fun addListener(observer: Observer<T>): Subscription {
    var uuid = UUID.randomUUID()
    while(observers.contains(uuid)) {
    Thread.sleep(1)
    uuid = UUID.randomUUID()
    }
    val subscription = Subscription(uuid, this)
    observers[uuid] = observer
    return subscription
    }
    fun unsubscribeListener(uuid: UUID) = observers.remove(uuid)
    fun unsubscribeAll(): Int {
    val num = observers.size
    observers.clear()
    return num
    }
    }
    :thread-please: 1
    e
    • 2
    • 3
  • s

    SecretX

    02/26/2021, 6:56 AM
    (DefaultDispatcher-worker-5 @coroutine#5) Subscribing 10000 listeners took 177ms
    (DefaultDispatcher-worker-4 @coroutine#4) Subscribing 10000 listeners took 178ms
    (DefaultDispatcher-worker-1 @coroutine#3) Subscribing 10000 listeners took 178ms
    (DefaultDispatcher-worker-3 @coroutine#2) Subscribing 10000 listeners took 178ms
    (DefaultDispatcher-worker-6 @coroutine#6) Subscribing 10000 listeners took 178ms
    (main @coroutine#1) Unsubscribing all 49962 listeners took 0ms
    u
    • 2
    • 10
  • r

    Rob

    02/26/2021, 3:14 PM
    Is there a way to use have a
    MutableStateFlow<T : Any>
    where the initial value is not set immediately? I am migrating from RxJava2
    BehaviorSubject<T : Any>
    . The value is not initialized until some process finishes. Observers of the value are transient. I would rather it not be a
    T?
    where I filter out the initial null value. Thanks!
    t
    g
    • 3
    • 11
  • v

    voben

    02/26/2021, 3:31 PM
    Say you have a fragment that’s observing a stateflow in the viewmodel. How do you know what event triggered that change in state? Is the only way to know by setting breakpoints in the viewmodel everywhere where the stateflow gets updated?
    w
    • 2
    • 3
  • j

    jeff

    02/26/2021, 3:51 PM
    This test fails:
    @Test
      fun `emitting too fast`() {
        val scope = CoroutineScope(Dispatchers.Default)
        val actionFlow = MutableSharedFlow<String>(extraBufferCapacity = 10)
        var success = false
    
        actionFlow
          .onEach { success = true }
          .launchIn(scope) // 1
    
        actionFlow.tryEmit("HELLO") // 2
        
    
        runBlocking {
          withTimeout(1000) {
            while (!success) {
              yield()
            }
          }
          success shouldBe true
        }
      }
    I understand why, I think, it's because the 'subscription' to actionFlow is launched (
    1
    ) and therefore hasn't happened yet by the time I try to emit (
    2
    ). Therefore, because `SharedFlow`s don't buffer or anything by default, the emission of "HELLO" is just dropped. My question is, what's the best way to make sure
    1
    is ready before I do
    2
    . I can imagine there's a way to use
    SharedFlow.subscriptionCount
    but that seems inelegant. Any better way?
    a
    • 2
    • 10
  • a

    Ahmed Ibrahim

    02/26/2021, 3:53 PM
    Is there an
    onEach
    variant but with
    onEachLatest
    instead? I have a flow that has an
    onEach
    operator on its chain, and in its body, there is a suspendCancellableCoroutine, and I want it to be cancelled when a new value is emitted, I tried looking around but couldn't find any.
    • 1
    • 1
  • e

    Erik

    02/26/2021, 6:47 PM
    I have an
    object
    with private construct-once properties (e.g.
    private val x = SomeConstructor()
    ) and public
    suspend
    functions that access these properties. The suspending funs all use
    withContext(myContext) {}
    to ensure they access the properties from the correct thread. How can I ensure that the properties are instantiated on that same thread? Would it be enough to use
    private val x by lazy { SomeConstructor() }
    as long as
    x
    is only accessed from within
    withContext(myContext)
    ? Will that guarantee that
    x
    is constructed on the thread(s) backing
    myContext
    ?
    m
    • 2
    • 2
  • b

    Big Chungus

    02/27/2021, 10:14 AM
    What would I use to basically get a channel or flow that can potentially send to itself? Basically async tail recursion where if the x condition is satisfied, you send channel item back, otherwise process the current item
    h
    • 2
    • 10
  • b

    Bee

    02/27/2021, 3:21 PM
    I am having difficulty getting the difference in behavior between
    runBlocking
    and
    coroutineScope
    , which I put into this question. Could someone help me with it, please?
    z
    • 2
    • 1
  • w

    william

    02/27/2021, 3:35 PM
    is there a way to do something like this for all modules in a project?
    // ignore these warnings
    kotlin.target.compilations.all {
        allKotlinSourceSets.forEach { sourceSet ->
            sourceSet.languageSettings.apply {
                useExperimentalAnnotation("kotlinx.coroutines.FlowPreview")
                useExperimentalAnnotation("kotlinx.coroutines.ExperimentalCoroutinesApi")
                useExperimentalAnnotation("io.ktor.util.KtorExperimentalAPI")
            }
        }
    }
    c
    b
    • 3
    • 20
  • b

    Big Chungus

    02/27/2021, 7:25 PM
    How would I transform a flow with multiple parallel coroutines? I saw .buffer() option, but that just does the transform on a single parallel coroutine to collector
    d
    • 2
    • 2
  • s

    spierce7

    02/28/2021, 1:09 AM
    If I want to make a server request, but also, at the same time subscribe to further updates of that data from a StateFlow (driven separately by something i.e. a push message telling the app the data is fresh), what would the best way to do that? Something to keep in mind is I need to pass exceptions from the server request though as well. I haven’t found an elegant way to do this without it getting messy.
    z
    a
    • 3
    • 14
  • t

    theapache64

    03/01/2021, 1:15 PM
    is lint lying or am doing it in a wrong way? 🤔
    g
    m
    • 3
    • 5
  • o

    Orhan Tozan

    03/01/2021, 6:16 PM
    Which Flow method do you happen to use more than the other? 1️⃣
    flatMapConcat { }
    2️⃣
    flatMapMerge { }
    3️⃣ i dont remember using any of them
    3️⃣ 13
    1️⃣ 3
    2️⃣ 6
    f
    e
    l
    • 4
    • 59
  • r

    Rechee Jozil

    03/01/2021, 10:44 PM
    A common pattern I've seen: Holding onto a job because you want to cancel the existing job if it's already in progress. Is there a better way to do this?
    z
    m
    g
    • 4
    • 8
  • s

    spierce7

    03/02/2021, 12:57 AM
    What’s the best way to test multiplatform coroutines that have
    delay
    in them?
    a
    m
    • 3
    • 5
  • a

    Aslam Hossin

    03/02/2021, 8:48 AM
    Having difficulties with suspendCancellableCoroutine. Could someone please help me to figure out what I missed? Caused by java.lang.IllegalStateException: Already resumed, but proposed with update kotlin.Unit at kotlinx.coroutines.CancellableContinuationImpl.alreadyResumedError(CancellableContinuationImpl.kt:447) at kotlinx.coroutines.CancellableContinuationImpl.resumeImpl(CancellableContinuationImpl.kt:412) at kotlinx.coroutines.CancellableContinuationImpl.resumeImpl$default(CancellableContinuationImpl.kt:388) at kotlinx.coroutines.CancellableContinuationImpl.resumeWith(CancellableContinuationImpl.kt:293) at $wrapStatusListener$$inlined$suspendCancellableCoroutine$lambda$1.onSuccess(Misc.kt:88) at java.lang.reflect.Method.invoke(Method.java) at com.twilio.chat.internal.RethrowingForwarder$RethrowingProxy.invoke(RethrowingForwarder.java:121) at java.lang.reflect.Proxy.invoke(Proxy.java:1006) at $Proxy11.onSuccess() at com.twilio.chat.internal.StatusListenerForwarder$1.run(StatusListenerForwarder.java:33) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7660) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
    suspend fun <T> wrapStatusListener(value: T, block: (StatusListener) -> Unit): T {
        return suspendCancellableCoroutine { continuation: CancellableContinuation<T> ->
            block(object : StatusListener() {
                override fun onSuccess() {
                    continuation.resume(value)
                }
    
                override fun onError(errorInfo: ErrorInfo) {
                    continuation.resumeWithException(
                           Exception(
                            code = errorInfo.code,
                            status = errorInfo.status,
                            errorMessage = errorInfo.message
                        )
                    )
    
                }
            })
        }
    }
    :stackoverflow: 1
    u
    k
    z
    • 4
    • 11
  • b

    Bradleycorn

    03/02/2021, 3:58 PM
    Android specific question re: coroutines ... is there any issue with doing something like this?
    class MyViewModel(): ViewModel() {
        private var job: Job = viewModelScope.launch {
            // Some long running async task, like polling a server or something
        }
    
        fun onSomeUIEvent() {
            job.cancel()
        }
    }
    n
    f
    +3
    • 6
    • 14
  • p

    Patrick Ramsey

    03/03/2021, 3:04 AM
    Does kotlin have an equivalent of twisted’s
    deferToThread()
    ? IE, a neat, packaged way to spawn a thread/run some blocking work on a thread pool, and monitor it from a coroutine which resumes the caller when the blocking code finishes?
    r
    • 2
    • 5
  • v

    Vsevolod Tolstopyatov [JB]

    03/03/2021, 3:50 PM
    📣 📣 📣
    kotlinx.coroutines
    1.4.3 and 1.4.3-native-mt are here! •
    CoroutineStart.UNDISPATCHED
    promoted to stable API • Better support of
    ThreadContextElement
    and its integrations • Proper support of
    onUndeliveredElement
    in unlimited channels • Various performance improvements and bug fixes Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.4.3
    :party-parrot: 4
    🎉 27
    o
    p
    • 3
    • 4
  • m

    mikehearn

    03/03/2021, 4:42 PM
    However, the replacement
    onReceiveOrNull
    is already imported, but, not being used.
    g
    • 2
    • 1
  • b

    Brian Carr

    03/03/2021, 8:15 PM
    Hello! I asked this over in #getting-started and it was suggsted that ask ask over here.
    m
    • 2
    • 4
  • m

    Manu Eder

    03/04/2021, 4:50 PM
    Not sure if this is the right place to ask, but is there a reason why for flows there is an imperative interface for generating flows, but no imperative interface for consuming flows, like you can with channels or iterators? Or did I just not find it? I understand the benefits in readability etc. of using flow combinators where possible, but it seems to me there are certain parsing-type problems which are just not easily / readably expressable with the current flow combinators. Here https://pl.kotl.in/G07SkQwGw is a playground where I've implemented something which preserves the cold-by-default behaviour of flows while allowing you to consume and transform flows imperatively. Code sample:
    // f1 is a flow of somewhat random numbers, no deeper meaning
        val f1 : Flow<Int> = flowOf(1, 1, 2, 3, 5, 8, 3, 1, 4, 5, 9, 4, 3, 7, 0, 7, 7, 4, 1, 5)
        /*
        Let's imagine that we are told f1 consists of "packets", which start with a length field followed by as many numbers
        as indicated in the length field. We want to transform f1 into a flow where each element is the sum of the numbers
        in the "payload" of one packet.
        */
        runBlocking {
            println("package sums:")
            f1.transformImperatively<Int, Int> {
                while (true) {
                    if (hasNext()) {
                        emit(sum(next()))
                    } else {
                        break
                    }
                }
            }.collect(::println)
        }
    code for sum:
    suspend fun (FlowIterator<Int>).sum( count : Int ) : Int {
        var s : Int = 0
        for (i in 1..count) {
            if( hasNext() ) {
                s += next()
            } else {
                break
            }
        }
        return s
    }
    It's not finished, more a proof-of-concept. (In particular, I haven't had time yet to try and understand flow cancellation, or the context preservation properties expected of flows, so don't expect it to behave correctly in that regard yet. Though I would very much expect it to be possible to make it behave correctly in that sense as well.) I would be happy about any kind pointers to discussions about similar things, reasons why something like this isn't or shouldn't be in kotlinx.coroutines, reasons why it might break down later on, etc.
    e
    a
    • 3
    • 23
  • s

    streetsofboston

    03/04/2021, 6:14 PM
    Question: Why would this be preferred
    private val _myFlow = MutableStateFlow<String>("")
    val myFlow: SharedFlow<String> = _myFlow.asStateFlow()
    over
    private val _myFlow = MutableStateFlow<String>("")
    val myFlow: SharedFlow<String> = _myFlow
    ? A MutableStateFlow is a StateFlow; why the extra call to
    asStateFlow()
    ?
    c
    l
    a
    • 4
    • 5
  • k

    Kris Wong

    03/04/2021, 7:56 PM
    are there any plans for a serial queue style scope that doesn't require a dedicated thread? similar to how GCD works.
    ➕ 1
    l
    • 2
    • 1
  • e

    Ellen Spertus

    03/04/2021, 9:26 PM
    I'm having trouble grasping something basic about coroutines (even though I understand concurrency in other programming languages). Why is it necessary for responsiveness to have both
    launch
    (which presumably puts something on another thread) and
    suspend
    functions, which enable that thread to be used for another coroutine? I'm working in the context of Android, where it's vital that the main thread not get blocked. Why isn't launching a database access, for example, sufficient to guarantee main thread responsiveness? Is the issue that there are a small number of worker threads so no single database access should monopolize one?
    c
    l
    • 3
    • 4
  • w

    william

    03/05/2021, 12:20 AM
    how can i tell when a receivechannel has closed? i'm not iterating over it in this case
    m
    • 2
    • 2
Powered by Linen
Title
w

william

03/05/2021, 12:20 AM
how can i tell when a receivechannel has closed? i'm not iterating over it in this case
.consumeAsFlow().onCompletion { ... }
?
m

mng

03/05/2021, 1:49 AM
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/is-active.html Maybe 'isActive' is what you're looking for?
View count: 3