https://kotlinlang.org logo
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
  • d

    Daniele B

    06/16/2021, 9:09 AM
    I would like to express a suspend function as a callback:
    suspend fun getMyObject() : MyObject {
       ...
       return myObject
    }
    
    val myApp = myCallback { myObject ->
       /* code using myObject */
    }
    how should I write the function
    myCallback
    ?
    k
    c
    • 3
    • 3
  • u

    ursus

    06/16/2021, 10:36 AM
    Is there some significant runtime overhead for CoroutineScope instance, i.e lets say having 30of them, vs 1 shared thats being injected?
    t
    e
    • 3
    • 2
  • t

    Tim Malseed

    06/17/2021, 3:03 AM
    I've got a StateFlow that doesn't seem to emit any values (classic StateFlow problem) I don't think this is due to object equality, but I can't figure out what's going on..
    g
    w
    +2
    • 5
    • 18
  • s

    samuel

    06/17/2021, 7:58 PM
    We’ve been using payloads and diffs in our recycler views to react to state changes for a long time now. One idea that came to mind was exposing a flow of state + lifecycle scope to our recycler view’s adapters and collecting the state (from each viewholder) and updating the viewholders’ UI that way. One benefit i see to this is our code complexity drastically reduces while also having a good UX (no flickering/glitches). Does anyone have thoughts on this, pros or cons to considering such an approach?
    o
    j
    • 3
    • 4
  • p

    py

    06/17/2021, 10:15 PM
    answer is: not exactly. It all works with the assumption that the underlying executor will throw if shutdown. I was looking at “bad” code that’s wrapping an android handler and not throwing if the task is rejected, hence blocking forever
    l
    z
    • 3
    • 8
  • z

    zak.taccardi

    06/18/2021, 3:50 AM
    Just to clarify - coroutines now requires Java 8 (with version
    1.5.0
    of the lib), which means all Android projects that consume it must enable Java 8 desugaring?
    d
    e
    • 3
    • 2
  • m

    Mark Allanson

    06/18/2021, 7:51 AM
    If I have a list of Deferred's created inside a
    supervisorScope
    using
    async
    . What is the most efficient way to await for the first failure of any of the jobs? At the moment I am looping the jobs, saving away successes, and capturing the first failure, then when that happens issuing a "controlled cancellation on the others" and using a yield (or delay) inside the tight loop, but it feels like there must be a better way of doing this
    e
    • 2
    • 7
  • t

    theapache64

    06/18/2021, 10:07 AM
    I am wondering if we can implement a
    suspend
    method in Java class. What's the correct way to do it? SO Thread: https://stackoverflow.com/questions/68032757/how-can-i-implement-kotlin-suspend-method-in-a-java-class
    d
    c
    • 3
    • 2
  • m

    mkrussel

    06/18/2021, 3:21 PM
    Trying to understand this section in the kotlin native-mt coroutine documentation.
    However, it is known to leak memory in scenarios involving concurrency under load, for example when multiple children coroutines running in different threads are simultaneously cancelled.
    Would multiple jobs launched like the above roughly at the same time, produce the leak.
    Untitled.kt
    • 1
    • 1
  • t

    Tiago Nunes

    06/18/2021, 4:20 PM
    Hi everyone, I'm trying to test a ktor call, which is a suspend function, in commonTest. Should I use
    runBlocking
    ,
    GlobalScope
    , or what? I've tried kotlinx-coroutines-test, to use
    runBlockingTest
    , but apparently this library is only for JVM?
    j
    d
    b
    • 4
    • 3
  • s

    SrSouza

    06/18/2021, 7:35 PM
    Hi folks, there is any CoroutinesContextElement/Key that says when is running inside a
    runBlocking
    ?
    d
    e
    • 3
    • 5
  • o

    okarm

    06/20/2021, 9:01 AM
    Can we get eyes and a priority check on this issue? Exceptions thrown from
    Dispatchers.Default
    fail to terminate the program and it was reported in November https://github.com/Kotlin/kotlinx.coroutines/issues/2398
    v
    • 2
    • 1
  • c

    Cody Mikol

    06/21/2021, 6:04 PM
    Hey all, question for a coroutine novice, I have a method that can be called concurrently and if a certain condition is met, I’d like to start a job with the first method that sees the condition is met, and then have the other threads wait for the result of that job. My first thought was to have some Atomic Semaphore / Lock that indicates one of the threads has claimed this job, but that would not allow for me to join on that result. What is the idiomatic way to do this in kotlin?
    z
    c
    t
    • 4
    • 8
  • f

    frankelot

    06/21/2021, 7:32 PM
    Is there a way to
    send
    something to an actor and “suspend” until the message was processed?
    c
    e
    • 3
    • 22
  • s

    Sourabh Rawat

    06/22/2021, 7:00 PM
    when to use "suspend function" vs "function returning Deferred"?
    d
    c
    g
    • 4
    • 6
  • l

    lhwdev

    06/23/2021, 5:30 AM
    Is there anything like 'daemon coroutine' in
    coroutineScope
    that will be cancelled if other things in it are completed? Normally tasks running in
    launch
    in it will cause
    coroutineScope
    not to return.
    e
    • 2
    • 4
  • p

    Patrik Åkerfeldt

    06/23/2021, 2:32 PM
    I'm trying to make firebase-admin calls coroutine-friendly. The api call returns an ApiFuture. I want to wrap that in a suspend function with a set timeout. The attached code is my approach to it but the timeout never seem to trigger if the third party request stalls for whatever reason. I'm trying to figure out if this is at all a sane approach or if I'm doing something wrong. Can I expect the
    withTimeout
    to trigger an exception after 5 seconds of no response?
    Untitled.kt
    a
    • 2
    • 3
  • p

    Pablo Schmid

    06/23/2021, 4:38 PM
    Hi, I'm new to coroutines and I'm trying to understand some basic behavior of async. The following code runs in 2 seconds and I understand that because I'm using async. What I don't understand is how this can happen if both asyncs are running on the same Thread (main)? Can coroutines run in parallel although they run in a single thread?
    import kotlinx.coroutines.*
    import kotlin.system.*
    fun main() = runBlocking {
        val time = measureTimeMillis {
            println("The answer is ${concurrentSum()} en ${Thread.currentThread()}")
        }
        println("Completed in $time ms en ${Thread.currentThread()}")    
    }
    suspend fun concurrentSum(): Int = coroutineScope {
        val one = async { doSomethingUsefulOne() }
        val two = async { doSomethingUsefulTwo() }
        one.await() + two.await()
    }
    suspend fun doSomethingUsefulOne(): Int {
        println("1 in Thread ${Thread.currentThread()}")
        delay(2000L) // pretend we are doing something useful here
        return 13
    }
    suspend fun doSomethingUsefulTwo(): Int {
        println("2 in Thread ${Thread.currentThread()}")
        delay(2000L) // pretend we are doing something useful here, too
        return 29
    }
    z
    d
    e
    • 4
    • 6
  • p

    Paul Woitaschek

    06/23/2021, 4:46 PM
    I think some time ago I read an article that suggested to always use the main dispatcher by default and only switch to sth else on demand. Can anybody recall if he read that too and where?
    w
    m
    • 3
    • 3
  • a

    Abhishek Dewan

    06/23/2021, 5:41 PM
    I am pretty sure that I am missing something obvious but in the following code the first emission from the notificationsViewModel StateFlow works but when I call the refresh function it doesn’t flow the updates through notificationsViewModel. What am I missing here? (Apologize about the naming conventions as they may be confusing)
    Untitled
    👍 1
    • 1
    • 1
  • a

    androidexpertmanish

    06/24/2021, 4:32 AM
    Hi I am new to coroutines. I am having an issue with delay function. I have a foreground service in which I am starting bluetooth scanning then delaying for 20 seconds and then calling stopScan. Now, scan result is start coming 20 seconds late, is it because of delay?
    g
    r
    • 3
    • 9
  • o

    obobo

    06/24/2021, 6:06 PM
    I'm thinking about building a flow around a kafka consumer; problem is that the consumer only allows me to call its methods from a single thread. I was able to implement this using coroutines fired by a single-threaded dispatcher and communicating via channels. But for a Flow-centered solution I build a flow using the
    flow{}
    builder, can I somehow guarantee that the code in the
    flow{}
    will run inside a specific dispatcher but the code that collects the results sent by `emit()`will run in a less-restricted dispatcher?
    k
    • 2
    • 1
  • a

    Ahaisting

    06/24/2021, 8:03 PM
    Hey y’all! I’m seeing some
    combine
    behavior that I don’t expect, hoping someone can help me shed some light. (putting code snippet in thread)
    j
    b
    • 3
    • 37
  • r

    Rak

    06/25/2021, 4:56 AM
    Hi, I am trying to write a test for my android app but I can’t get it to work. I never receive the ViewState.Info state. Instead I only get the initial Loading state. The code is in the reply thread.
    • 1
    • 1
  • j

    julioromano

    06/25/2021, 8:51 AM
    I’d like to create a Unit returning suspend function which launches another coroutine inside it and must not return until that coroutine has finished. Is this “pattern” a good way for implementing this?
    suspend fun myFunction(myParam: String): Unit = myScope.launch {
    	doSomethingElseSuspending()
    	withContext(anotherContext) { doSomeOtherStuffInTheOtherContext(myParam) }
    }.join()
    The rationale is that the caller of
    myFunction
    should not care of what’s happening inside it, the caller merely calls a suspending function (
    myFunction()
    ) that suspends until all work done inside it is done and then either throws or returns Unit.
    b
    j
    • 3
    • 5
  • w

    William Reed

    06/25/2021, 5:58 PM
    in my program i have multiple commands that i want to execute (where a command is something that is triggered, and polled upon until it completes). only one command can be executed at a time (limitation on the remote system). If i was only doing one of these at a time i would just call my
    suspend fun
    and wait for the result. however i am calling multiple `suspend fun`s from throughout my code base. I’m trying to think of a way to group these together and allow them to queue since each of the call sites uses a separate context/scope. another requirement is that if a particular command completes, it can cancel all remaining commands that are queued up. my first attempt at it in the thread -->
    c
    • 2
    • 4
  • a

    Alejo

    06/27/2021, 2:23 PM
    Hi everyone!  I want to update my app behavior depending on if a user is touching the screen or not. So I came with the idea of having a MutableSharedFlow that emits user interaction and collecting the values with collectLatest. The problem is that I'm only interested in the last event and would want to drop all older processing. How could I achieve this? The code looks like this:
    val userInteracting = MutableSharedFlow<Unit>(replay = 0)
    
    onEvent(){
        coroutineScope.launch {
            userInteracting.emit(Unit)
        }
    }
    
    coroutineScope.launch {
        userInteracting.collectLatest {
            showSky.value = false
            delay(5000)
            showSky.value = true
        }
    }
    m
    c
    • 3
    • 23
  • b

    bloodshura

    06/27/2021, 4:12 PM
    How'd I go implementing a
    List#sortedWith
    that takes a comparator which can be suspended? Suppose I'd need something like this:
    someList.sortedWith { o1, o2 -> suspendedComparison(o1, o2) }
    Where
    suspendedComparison
    is a function which returns
    Int
    (satisfying
    Comparator
    ) and is a
    suspend fun
    ...
    m
    e
    • 3
    • 11
  • s

    Sudhir Singh Khanger

    06/28/2021, 2:13 PM
    What are possible negatives of running a
    Retrofit
    call without suspend keyword from a
    Coroutine
    ?
    u
    i
    +3
    • 6
    • 14
  • j

    Justin Tullgren

    06/29/2021, 7:22 PM
    Hi, does anyone have an example of a channel/flow that acts like a blocking priority queue? Channels are fine for acting like a BlockingQueue in a non-blocking way but I need the offer to the queue to do the priority insert operation which channels dont have
    👍 1
    • 1
    • 1
Powered by Linen
Title
j

Justin Tullgren

06/29/2021, 7:22 PM
Hi, does anyone have an example of a channel/flow that acts like a blocking priority queue? Channels are fine for acting like a BlockingQueue in a non-blocking way but I need the offer to the queue to do the priority insert operation which channels dont have
👍 1
I don't want to use the BlockingPriorityQueue as it blocks the thread, I am looking for suspension
View count: 4