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

    Stan Potemkin

    01/11/2021, 4:29 AM
    Can someone please tell why.. I have a shared flow that emits a value when user taps a button:
    sharedFlow.collect { println("first") }
    
    sharedFlow.collect { println("second") }
    But actually 10 taps results in 10 prints of "first" message and never prints the "second" one. Does the shared flow accept only one collector, or could it's behavior widely depend on configuration and usage?
    g
    k
    • 3
    • 42
  • a

    Ali Albaali

    01/11/2021, 10:53 AM
    Hi, I'm trying to get progress when loading data in my application and I've come to two solutions One of them uses flow:
    suspend fun flowProgress(block: (Flow<Int>) -> Unit) {
        block(
            flow {
                do {
                    val progress: Int // .... getting progress
                    emit(progress)
                } while (true)
            }
        )
    }
    The other uses plain callback function:
    suspend fun intProgress(block: (Int) -> Unit) {
        do {
            val progress: Int // .... getting progress
            block(progress)
        } while (true)
    }
    Can somebody tell me what's the difference between these two and why should I go with one over the other?
    g
    • 2
    • 61
  • p

    Pratik Tandel

    01/11/2021, 5:47 PM
    A somewhat trivial question but i couldn’t find a straightforward answer by googling; what’s the best way to convert one of the many Rx / Reactive types to a coroutine? Things like
    Single
    ,
    Flowable
    etc
    g
    • 2
    • 6
  • z

    zak.taccardi

    01/11/2021, 7:11 PM
    I need a flow builder that emits
    Unit
    every
    X
    milliseconds while it has a subscriber. What’s the idiomatic approach for this?
    s
    g
    • 3
    • 4
  • r

    rednifre

    01/12/2021, 3:45 PM
    So, no .forEach but more like .forLatest... or does .forEach not look into the past anyways?
    z
    • 2
    • 2
  • p

    Pablo

    01/12/2021, 4:17 PM
    Anyone of you can explain how retrofit / room are doing the main-safety stuff? I know that if I put suspend I can avoid the
    withContext(<http://Dispatchers.IO|Dispatchers.IO>)
    but what if I have some mappers and some business logic? Is it safe to remove the
    withContext(<http://Dispatchers.IO|Dispatchers.IO>)
    ?
    n
    l
    • 3
    • 15
  • r

    Rechee Jozil

    01/12/2021, 6:26 PM
    Let's say you are within a suspend function... What's the most pragmatic way to cancel your execution? Should you just throw a cancellation exception? Or maybe somehow grab the current job and cancel that?
    z
    • 2
    • 5
  • v

    vineethraj49

    01/12/2021, 7:54 PM
    has anyone tried to use coroutines within
    StreamingOutput
    before?
    j
    • 2
    • 2
  • w

    WukongRework.exe

    01/12/2021, 11:02 PM
    I remember from somewhere that putting a loop inside of a coroutine is a pretty bad idea but I cant remember why. Could someone please explain why?
    z
    j
    +2
    • 5
    • 6
  • m

    Mark

    01/13/2021, 2:31 AM
    How to avoid accidentally catching
    CancellationException
    ? For example, any inline (not suspending) higher order function could innocently be catching
    Exception
    and converting to some sealed class. It knows nothing about coroutines and so would have no reason to give special treatment to
    CancellationException
    .
    fun main() {
        runBlocking {
            val job = launch {
                test {
    			    delay(1000L)
                    println("finished long delay")
                }
                println("finished test")
            }
            delay(100L)
            job.cancel()
        }
    }
    
    inline fun test(block: () -> Unit) {
        try {
            block()
        } catch (e: Exception) {
            println(e.toString())
        }
    }
    
    // kotlinx.coroutines.JobCancellationException: StandaloneCoroutine was cancelled; job="coroutine#2":StandaloneCoroutine{Cancelling}@de0a01f
    // finished test
    m
    e
    a
    • 4
    • 11
  • p

    Pablo

    01/13/2021, 8:12 AM
    If I have my presenter that has a
    CoroutineScope
    as a parameter with dagger like
    fun provideFragmentScope(fragment: MyFragment): CoroutineScope = fragment.lifecycleScope
    if on
    onDestroyView
    I put
    lifecycleScope.coroutineContext.cancelChildren()
    then is a good praxis to cancel coroutines? Note I'm not using
    ViewModel
    so I have to cancel it manually...
    l
    • 2
    • 5
  • s

    Simon Lin

    01/13/2021, 8:39 AM
    How do I set the flow to start collecting only when the data meet certain conditions. For example:
    flowOf(1, 2, 3, 2, 1, 2, 3)
        .startCollectWhen { it == 3 }
        .collect { print(it) }
    
    // Result: 3, 2, 1, 2, 3
    d
    • 2
    • 1
  • p

    Peter Ertl

    01/13/2021, 10:40 PM
    does kotlin flow currently support creating batches of items, e.g. for executing batched sql inserts? like that (pseudo code): flow.batch(size=20).collect { batchOfUpTo20ItemsFromFlow -> /* do something */ }
    g
    • 2
    • 2
  • j

    jeff

    01/13/2021, 11:01 PM
    How can I have a SharedFlow buffer emissions that come while there are no subscribers?
    p
    • 2
    • 3
  • f

    FunkyMuse

    01/14/2021, 8:01 AM
    Hello devs, which one do you think it's better to be used and why? 1. private val stateData = MutableStateFlow<State>(State.Idle) val state: StateFlow<State> get() = stateData Or 2. private val stateData = MutableStateFlow<State>(State.Idle) val state: StateFlow<State> = stateData
    l
    j
    r
    • 4
    • 17
  • r

    Rechee Jozil

    01/15/2021, 1:30 AM
    This is scary. I just published my first blog 🙏🏼 . I breakdown the suspend function. Let me know your thoughts! https://recheecodes.com/kotlin-coroutines-suspend-function/
    🙌 1
    g
    i
    • 3
    • 4
  • p

    parth

    01/15/2021, 2:27 PM
    (crossposting here as well)
    m
    f
    • 3
    • 6
  • e

    eygraber

    01/15/2021, 7:52 PM
    I'm getting a report of a StackOverflowError crash in an Android app (can't repro locally). It looks like it's coroutines related, but the crash happens in a kotlin.text function. How can I debug something like this?
    Untitled
    r
    s
    • 3
    • 4
  • w

    WukongRework.exe

    01/16/2021, 6:29 AM
    I remember from a KotlinConf about testing with coroutines that multiple coroutine scopes can be on the same thread, am I remember this correctly? also if this ^ is true, is there a way to ensure that multiple coroutine scopes are on the same thread?
    l
    • 2
    • 1
  • s

    Shmuel Rosansky [G]

    01/17/2021, 5:42 PM
    Any ideas why this prints: Inner Value: 0 Outer
    fun main() {
       println("Outer")
       
       CoroutineScope(Dispatchers.Default).launch {
           getFlow()
                .onEach { println("Value: $it") }
                .collect()
       }
    }
    
    
    fun getFlow() = callbackFlow<Int> {
       println("Inner")
       delay(1)
       sendBlocking(0)
    }
    Shouldn't
    Outer
    get printed first?
    m
    • 2
    • 8
  • m

    Michal Klimczak

    01/17/2021, 9:09 PM
    are
    CoroutineScopes
    cheap? Can I just create a
    MainScope()
    or sth for e.g. every usecase execution or does it come with some significant overhead? it's a specific use case in kotlin multiplatform where I would rather create it every time than reuse it for a much more concise code.
    d
    • 2
    • 1
  • b

    bjonnh

    01/18/2021, 12:21 AM
    How does one debug coroutines just from the logs, I got an exception (TimeoutCancellationException) that appeared randomly but it never said where it was coming from so I had to dissect my program to finally find the ktor call that was responsible. Is there something that would allow to log where the exception really happened (without having a debugger attached all the time as it is not possible in production)?
    m
    • 2
    • 4
  • n

    nitrog42

    01/18/2021, 3:44 PM
    myFlow.previousMap { previousValue, currentValue -> }
    w
    d
    +2
    • 5
    • 15
  • b

    Byron Katz

    01/18/2021, 5:05 PM
    I have a program, a web server, that currently uses a cached thread pool executor with a default thread factory. Is there an easy way I can switch in coroutines there? I tried with project loom and it worked beautifully, is it similar in coroutines?
    s
    c
    z
    • 4
    • 8
  • j

    james

    01/19/2021, 2:28 PM
    When working with Java
    Future
    or
    CompletableFuture
    in JVM > 8 within
    suspendCoroutine
    what's the suggested pattern for interaction. From what I can tell, the
    suspendCoroutine
    is designed for an asynchronous callback but from what I can tell JDK 11, 12, 13 and 14 don't have a way to implement a CompletionStage interface.
    l
    y
    m
    • 4
    • 9
  • n

    Nikky

    01/19/2021, 5:42 PM
    how to i take the first element fro ma flow and then consume the rest with collect ? seems like when i use
    take
    it closes the flow
    l
    d
    • 3
    • 14
  • j

    johnaqel

    01/20/2021, 2:16 AM
    Has there been any recent talk of suspend getters/setters for properties? I would really love to see this. Anyone know if it’s being planned?
    s
    v
    • 3
    • 2
  • s

    samuel

    01/20/2021, 12:51 PM
    i keep getting this crash while using 
    debounce
     on android:
    java.lang.AbstractMethodError: abstract method "kotlinx.coroutines.DisposableHandle kotlinx.coroutines.Delay.invokeOnTimeout(long, java.lang.Runnable, kotlin.coroutines.CoroutineContext)"
    this is an example of how it arises
    myScope.launch {
        myFlow
        .debounce(500)
        .collect {
            Timber.e("received input $it")
        }
    }
    Anyone know what causes this?
    • 1
    • 1
  • c

    christophsturm

    01/20/2021, 2:24 PM
    is there a way to get the number of items in a channel (like queue.size) ?
    d
    • 2
    • 3
  • s

    Slackbot

    01/20/2021, 4:55 PM
    This message was deleted.
    ❓ 1
    s
    t
    • 3
    • 2
Powered by Linen
Title
s

Slackbot

01/20/2021, 4:55 PM
This message was deleted.
❓ 1
s

streetsofboston

01/20/2021, 5:04 PM
Detroit2002-2017&
t

taer

01/20/2021, 7:42 PM
horse battery staple
😅 1
View count: 10