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

    etolstoy

    09/16/2021, 3:54 PM
    Hey all! We’re considering folding coroutines internal calls in the IDE console output to leave only business logic on the stacktrace thus making analysing them easier. Folding means that all the lines (including the first line that matches a given at
    kotlinx.coroutines.
    prefix) will not be shown unless you click on 
    <3 internal lines>
    . After one clicks on this caption — all the underlying folded lines will be shown to the user. Folded code:
    at my.business.Logic.f(Logic.kt:30)
    at my.business.Logic.g(Logic.kt:150)
    at my.business.Logic.main(Logic.kt:99) <3 internal lines>
    at not.mine.but.also.BusinessLogic.main$1(BusinessLogic.kt:20)
    at not.mine.but.also.BusinessLogic.main(BusinessLogic.kt:19)
    Unfolded code:
    at my.business.Logic.f(Logic.kt:30)
    at my.business.Logic.g(Logic.kt:150)
    at my.business.Logic.main(Logic.kt:99)
    at kotlinx.coroutines.invokeAsync(Coroutines:999)
    at kotlinx.coroutines.applySuspend(Coroutines:18)
    at kotlinx.coroutines.runBlocking(BlockingCoroutines:555)
    at not.mine.but.also.BusinessLogic.main$1(BusinessLogic.kt:20)
    at not.mine.but.also.BusinessLogic.main(BusinessLogic.kt:19)
    To understand the possible consequences on user experience we want to know how you feel about seeing or not seeing coroutine internal stuff in your stacktraces (please note that they will be still available via clicking on <N lines folded>). And if you need them, it would be interesting to understand your specific use cases. Please, share your thoughts in the thread.
    :yes: 12
    b
    f
    l
    • 4
    • 5
  • v

    Vikas Singh

    09/16/2021, 4:42 PM
    How can I use lifecyclescope in a class which does not have any lifecycle, Passing the context is it a good approach ?
    j
    • 2
    • 5
  • n

    Norbi

    09/17/2021, 10:05 AM
    Do I understand correctly that if I catch an exception in a coroutine I should always check if it is a
    CancellationException
    ? Eg.:
    suspend fun etc() {
        try {
            someOtherSuspendFun()
        } catch (e: Exception) {
            if (e is CancellationException) {
                throw e // The operation has also failed but I should not throw WrapperException because it will interfere with the cancellation mechanism
            } else {
                throw WrapperException("Operation failed", e)
            }
        }
    }
    (The above is pseudo code, I have not tried it.) Thanks.
    s
    o
    e
    • 4
    • 13
  • r

    ribesg

    09/17/2021, 11:26 AM
    How do I make a state flow that: • emits its value immediately every time it changes • emits its value periodically X seconds after it changes (and keeps doing it until it changes) • don’t emit anything when the value is null (if it’s changed to null and periodically) I know how to make a flow that basically combines the origin state flow with an independent periodic flow re-emitting the value of the state flow, but it’s not exactly what I want. I found no simple way to make a timer either
    j
    m
    +3
    • 6
    • 11
  • p

    PHondogo

    09/18/2021, 7:06 AM
    Hello! How to distinguish if cancellation come from parent or child?
    l
    • 2
    • 5
  • f

    Fudge

    09/18/2021, 8:21 AM
    Hey, any idea why would a
    .collect {}
    call of a
    MutableStateFlow
    not work after the initial value? Basically, I create a
    MutableStateFlow
    in one place and call
    emit
    (multiple times) there, and at the same time call
    .collect {}
    in another place, and the callback of
    collect
    is not executed, except for the initial value. I can clearly see the state of the
    Flow
    is changing, but
    collect
    is just not working. I'm also absolutely sure the
    collect
    call is not getting canceled, as I have tried catching
    CancellationException
    . The context is a Jetpack Compose app, maybe it's some bug there? SOLVED: the problem was emitting the same list to the StateFlow. Even though the list is changing, its reference has not, and coroutines treat it as the same value, and concludes no new value needs to be emitted. Hence
    collect
    callback is not called after the initial value.
    a
    u
    • 3
    • 17
  • c

    Chachako

    09/19/2021, 12:17 PM
    How do I use
    launch { send(..) }
    in
    produce {}
    and ensure I can receive them in
    produce.consumeEach
    ?
    j
    • 2
    • 10
  • k

    K Merle

    09/20/2021, 8:32 AM
    Anyone experienced issue with
    previousBackStackEntry
    ? It's always null in case:
    val navController: NavHostController = rememberNavController()
    val previousBackStackEntry = navController.previousBackStackEntry
    and works correctly when has these 2 extra lines:
    val navController: NavHostController = rememberNavController()
    val currentState by navController.currentBackStackEntryAsState()
    val currentRoute: String? = currentState?.destination?.route
    val hasPreviousBackStackEntry = navController.previousBackStackEntry
    c
    • 2
    • 3
  • x

    Xenex

    09/20/2021, 2:56 PM
    Hi, I am starting a coroutine in a viewmodelscope triggered in the onPause state of my fragment. The coroutine just need to update a value in the data store pref. Some of my users get a nullpointer exception. I think its because of the speed of closing the fragment and the vm. My idea is to start the coroutine in a globalscope, is this a good approach? Thank you
    l
    s
    r
    • 4
    • 8
  • c

    CLOVIS

    09/20/2021, 7:34 PM
    I'm trying to implement something similar to lazy, but suspending. At the start of the program the value is empty, on first access I want to compute it, then reuse the same value throughout the program's lifetime. The easiest solution would be a lock/mutex, however it seems like they are quite expensive, so seem a bit overkill (since the data is immutable, locking is unnecessary after it is initialized)
    m
    r
    +2
    • 5
    • 7
  • o

    Orhan Tozan

    09/21/2021, 1:59 PM
    I'm looking at the implementation of
    Flow.debounce()
    and I saw it's quite complex. Now thinking about it, can't debounce be simplified to the following implementation?:
    fun Flow.debounce(timeoutMillis: Long) = transformLatest {
        delay(timeoutMillis)
        emit(it)
    }
    m
    e
    u
    • 4
    • 18
  • i

    ianbrandt

    09/21/2021, 4:20 PM
    Apologies if this has been asked before, but I'm not finding anything via search. Are there plans to cover
    SharedFlow
    and
    StateFlow
    under https://kotlinlang.org/docs/? If so, is there a related YouTrack/GitHub issue that could be followed and contributed to? Not that the KDocs aren't good, but it seems like a rather important component of the API, and I'm not seeing any mention of it on the #kotlin-website at all.
    ➕ 1
    e
    u
    • 3
    • 7
  • l

    leandro

    09/22/2021, 7:40 PM
    how can i have my kmp project use the latest coroutines-core and enforce native-only targets to use the -native-mt variant? I came up with a solution that had me replace my iosMain sourceSet with both iosArm64Main and iosX64Main and duplicate all its code.
    j
    f
    • 3
    • 14
  • b

    brabo-hi

    09/22/2021, 11:07 PM
    Hi, i am using sqldelight to get data from database as flow, however the flow is not being collected whenever a new item is added
    val players: Flow<List<HockeyPlayer>> = 
      playerQueries.selectAll()
        .asFlow()
        .mapToList()
    
    players,collect{
       // i am not getting new list when item is added, i only receive data once
    }
    What could i be doing that is not right ?
    r
    t
    • 3
    • 9
  • s

    Scott Christopher

    09/23/2021, 10:31 AM
    I have a function that wants to be able to spawn a new coroutine via
    launch
    but don't want to dictate which CoroutineScope it is attached to, so I have created it as an extension method to
    CoroutineScope
    so
    launch
    can be called against it. This approach feels like it is guarded pretty heavily against through the use of
    coroutineScope
    and friends - is there a more idiomatic way I should be spawning new tasks in the context of the calling function, or is this approach considered okay?
    🆗 1
    c
    b
    j
    • 4
    • 16
  • m

    mkojadinovic

    09/24/2021, 12:36 PM
    Hi, I am trying to use coroutines in my spring boot project. I am using RestTemplate for networking which is doing blocking calls. Is it safe if I do next:
    private suspend fun getSomething() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            RestTemplate().exchange(
                "url", <http://HttpMethod.POST|HttpMethod.POST>, HttpEntity("body"), String::class.java
            )
        }
    Will this produce many threads to wait, or I am safe that this will use some limited thread pool? What if I want to limit thread pool size to 2, will it also work?
    j
    u
    • 3
    • 13
  • p

    Paul Woitaschek

    09/24/2021, 12:43 PM
    Is there a built in equivalent of
    Observable.never()
    ?
    l
    m
    +3
    • 6
    • 16
  • m

    Mike Speed

    09/24/2021, 1:22 PM
    I have a suspend function:
    private suspend fun getThing(){...}
    How can I set a minimum return time on this? So it will only return if at least 2000ms have passed, for example?
    p
    c
    +3
    • 6
    • 22
  • m

    Michael Strasser

    09/26/2021, 11:48 AM
    I have a function to receive a batch of items from a
    Channel
    , returning a list of items after
    timeoutMs
    milliseconds (the list might be empty). Here is the code:
    public suspend fun <E> receiveBatch(
        channel: ReceiveChannel<E>,
        timeoutMs: Long,
    ): List<E> {
        val batch = mutableListOf<E>()
        withTimeoutOrNull(timeoutMs) {
            for (item in channel) {
                batch.add(item)
            }
        }
        return batch
    }
    In simple testing everything is fine, but under load sometimes an item is not added to a list and is lost. What I think happens is that
    withTimeoutOrNull
    times out between receiving an item from the channel and adding it to the list. Does anyone have a solution for this issue, or a better design for what I am trying to do?
    e
    • 2
    • 7
  • s

    Stylianos Gakis

    09/26/2021, 6:04 PM
    A question about doing parallel async work using map. (More in Thread 🧵)
    👀 1
    e
    • 2
    • 4
  • a

    Albert

    09/27/2021, 8:03 AM
    In a project I ran into something that affected the performance. I implemented 2 methods for comparisons on speed.
    without_actor
    runs in about ~10ms for 100_000 messages
    with_actor
    runs in about ~4000ms for 100_000 messages Is this caused by some context switching what is happening internally, or related how locking is done internally?
    Test_kt.cpp
    b
    • 2
    • 1
  • p

    Pablo

    09/27/2021, 2:02 PM
    Does it make sense to have a job and does not assign it to the
    launch{}
    ? Example :
    private val job: Job? = null
    
    internal class Foo : CoroutineScope {
      override val coroutineContext: CoroutineContext
       get() = Dispatchers.Main + Job!!
    
       ...
    
       private fun bar() {
        job = Job()
    
        launch { .... }
       }
    
       override onDetach() {
        job.cancel()
       }
    }
    Does it really cancel the launch?
    🇳🇴 1
    o
    m
    +2
    • 5
    • 53
  • u

    ursus

    09/28/2021, 2:07 AM
    Hi,
    class Foo {
        private val scope = CoroutineScope(SupervisedJob() + Dispatchers.Main.immediate)
    
        fun init() {
            println("a")
    
            scope.launch {
                println("b")
    
                flowOf("hello")
                    .collect {
                        println("c")
                    }
            }
    
            println("d")
        }
    }
    I'm pretty sure this emmited printed
    a, b, c, d
    in the past when using immediate main dispatcher on android but now it emits
    a, d, b, c
    Is there a way to make this blocking as it was in rxjava? I thought this exactly was the difference between
    Dispatchers.Main
    and
    Dispatchers.Main.immediate
    e
    l
    +2
    • 5
    • 58
  • l

    luke_c

    09/28/2021, 3:30 PM
    In the context of Android and replacing SingleLiveEvent. can anyone explain why a BUFFERED Channel seems to be preferred to the default RENDEZVOUS Channel?
    w
    u
    • 3
    • 9
  • b

    benkuly

    09/29/2021, 6:12 AM
    Can I do the follwing, when using
    flow
    and
    stateIn
    or does it has unpredictable side effects. It does not feel right to pass
    this
    into
    stateIn
    . Does
    doSomething()
    ever return or will it suspend infinite, because the scope is used by
    stateIn
    ?
    suspend fun doSomeThing() = coroutineScope {
        val someState = someFlow.stateIn(this)
        ...
    }
    l
    m
    • 3
    • 9
  • b

    Besto

    09/29/2021, 4:11 PM
    Hi 😊, I have a question about coroutine flow and viewmodel scope. I have a case when I register to a flow in my
    onStart()
    method in my Fragment A. This flow is attached to the
    viewModelScope
    . My question is: when I open another fragment and return to my Fragment A
    onStart
    is called again and the register for the flow is called as well, so the flow is called twice without cancel it as it's attached to the
    viewModelScope
    and the
    onCleared
    method was not called yet . How do you handle this case to avoid keeping emitting data to the view when the view is not attached ?
    l
    o
    • 3
    • 4
  • n

    nilTheDev

    10/01/2021, 9:15 AM
    Why can't we call
    launch
    or
    async
    from
    suspend
    function directly.
    suspend
    functions get called from a
    coroutine
    . Why can't it use that context. If we create a new
    coroutineScope
    inside a
    suspend
    function then would the new
    coroutines
    be attached to the parent that called the
    suspend
    function? So that these get cancelled when the parent get cancelled.
    j
    j
    o
    • 4
    • 4
  • k

    K Merle

    10/01/2021, 12:43 PM
    How to emit the same value with StateFlow? In my case, it's just Unit that I'd like to emit.
    l
    • 2
    • 1
  • b

    benkuly

    10/01/2021, 5:25 PM
    I want to use
    MutableStateFlow
    as a cache for a database (sqldelight). It means, that e. g. I have
    fun getKeysForUser(userId:String):MutableStateFlow<Keys?>
    , which first looks in the cache (just a MutableMap) if it contains a matching MutableStateFlow and if not, creates one with an initial value from the database. It then also launches a coroutine to collect from the MutableStateFlow and write to the database on changes. If there are no subscribers anymore (except from the db-collect), I want to remove it from the cache. What is the best way to do it and does this whole idea work?
    c
    • 2
    • 2
  • a

    AmrJyniat

    10/02/2021, 9:42 AM
    I want to combine multiple flows by
    combine
    function in variable x as following:
    val x = combine(flow1, flow2) { (flow1, flow2) ->
        listOf(flow1, flow2)
    }
    when I call collect on x flow the result will be empty because flow1 and flow2 not ready yet, so I want to trigger collect on each flow gets ready to get latest data always.
    d
    s
    n
    • 4
    • 5
Powered by Linen
Title
a

AmrJyniat

10/02/2021, 9:42 AM
I want to combine multiple flows by
combine
function in variable x as following:
val x = combine(flow1, flow2) { (flow1, flow2) ->
    listOf(flow1, flow2)
}
when I call collect on x flow the result will be empty because flow1 and flow2 not ready yet, so I want to trigger collect on each flow gets ready to get latest data always.
d

Dominaezzz

10/02/2021, 9:54 AM
What do you mean by not ready yet?
a

AmrJyniat

10/02/2021, 10:02 AM
flow1 and flow2 are data from API which take some time to get ready.
d

Dominaezzz

10/02/2021, 10:24 AM
So? If it takes a while then the flow while suspend for a while.
☝️ 2
s

stojan

10/02/2021, 2:30 PM
flow1.onStart { emit(defaultValue) }
And the same for flow2
n

nilTheDev

10/02/2021, 6:55 PM
Isn't it normal that flows would take time to emit values? The consumer will wait then.
View count: 8