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

    madsbf

    02/03/2019, 10:10 AM
    I'm running into an issue when using select, and I might just be missing something very simple. Maybe someone here can spot what I'm doing wrong? I have the following code:
    suspend fun select(contentMap: Map<Content, VideoContentItemHolder>) = coroutineScope {
        select<Content> {
            contentMap.forEach { content, itemHolder ->
                launch { itemHolder.onClick() }.onJoin {
                    content
                }
            }
        }
    }
    VideoContentItemHolder.onClick() is a suspending function. Basically I am waiting for any of the itemHolder.onClick() to complete, and then returning the associated Content-object. I have attached the debugger to see that onClick() successfully completes for one of the itemHolders and I enter the onJoin-block, but the select clause never gets a result. So anyone waiting for the result is suspended indefinitely.
    a
    b
    11 replies · 3 participants
  • d

    dave08

    02/03/2019, 6:05 PM
    I guess it would have been nice to have a
    getCompletedOrNull()
    that returns a null instead of throwing... so currently the only way is to
    runCatching { deferred.getCompleted() }.getOrElse { defaultValue }
    ?
    a
    c
    4 replies · 3 participants
  • t

    trathschlag

    02/04/2019, 9:00 AM
    Is there any (planned) concept of priorities for coroutines? I imagine an example where I want some specific kind of work – i.e. user interaction handling – to be always executed first, while some cpu intensive work without real time requirements should be handled as soon as all higher priority continuations have been worked on.
    u
    g
    +1
    8 replies · 4 participants
  • d

    Dalinar

    02/04/2019, 11:52 AM
    I want to replace the
    GlobalScope
    in `GlobalScope.async { }`but without using
    coroutineScope { }
    - I mean I want to write
    x.async{ }
    - how do I do that? what should
    x
    be? to make it the equivalant of doing
    coroutineScope { }
    ? is this possible? the reason I ask is because it requires a lot of reworking to use
    coroutineScope { }
    for this section of code
    g
    15 replies · 2 participants
  • d

    Dalinar

    02/04/2019, 12:43 PM
    I understand that `suspend fun`s can be suspended... what happens when it (the suspend fun) calls a non-suspend
    fun
    ? can the code in that
    fun
    also be suspended?
    s
    4 replies · 2 participants
  • s

    simon.vergauwen

    02/04/2019, 1:25 PM
    How can I cancel a coroutine I started with
    startCoroutineCancellable
    ?
    a
    v
    19 replies · 3 participants
  • k

    koufa

    02/04/2019, 2:04 PM
    How can I catch errors thrown from/in a
    launch
    coroutine? Is it only possible by using
    coroutineScope
    and add a try catch around it?
    y
    1 reply · 2 participants
  • b

    Bernhard

    02/04/2019, 2:12 PM
    does runBlocking create a new coroutine scope so that your jobs inside of it won’t leak on exceptions
    g
    5 replies · 2 participants
  • p

    pardom

    02/04/2019, 4:28 PM
    Hey, all. 👋 Is there a platform agnostic
    CoroutineDispatcher
    (i.e. not
    Dispatchers.Main
    ) that enforces a calling thread? I want to launch some tasks that return to the calling thread.
    g
    5 replies · 2 participants
  • s

    streetsofboston

    02/04/2019, 6:10 PM
    I have a
    ReceiveChannel
    that the caller can use to receive data sent from repeated callback. If something goes wrong, the
    Channel
    implementing the returned
    ReceiveChannel
    is closed with a
    Throwable
    . How can I catch this throwable? I can’t find a method on a
    ReceiveChannel
    that takes a callback function to handle a side-effect of closing a channel (with or without an error).
    e
    r
    4 replies · 3 participants
  • b

    bdawg.io

    02/05/2019, 3:09 AM
    Are there any previews available for the designs going towards cold channels?
    g
    3 replies · 2 participants
  • a

    altavir

    02/05/2019, 7:20 AM
    If we are talking about cold channels, are we talking only about cold start, or also about cold propagation? Because cold start is very simple thing to achieve without any additional complexity
    g
    2 replies · 2 participants
  • s

    spierce7

    02/05/2019, 6:14 PM
    Is there anything that is equivalent to an RxJava
    Subject
    with kotlinx.corotuines? There are too many edge cases with
    Channel
    where I risk losing events, and having to deal with them all the time is exhausting.
    a
    s
    +2
    60 replies · 5 participants
  • s

    spierce7

    02/05/2019, 7:21 PM
    Is there any way to match a
    BehaviorSubject
    with a
    BroadcastChannel
    ?
    ConflatedBroadcastChannel
    allows for the loss of events after subscription, while
    BehaviorSubject
    guarantees all events to be delivered. I've tried swapping to an
    ArrayBroadcastChannel
    to help ensure all events are delivered, but I have no way to ensure that the current value is delivered to a new subscriber upon a new subscription being opened. Any suggestions?
    j
    3 replies · 2 participants
  • d

    Dico

    02/05/2019, 9:02 PM
    @spierce7 https://gist.github.com/Dico200/2879fcbd205a31d1adcf3bab1aea6882 I wrote this for you. Hope it works.
    s
    2 replies · 2 participants
  • k

    Kulwinder Singh

    02/06/2019, 7:38 AM
    here
    firstAction()
    will be called even if i cancel job while coroutine is suspended by delay, what i'm doing wrong here ?
    job__cancelChildren___not_canceling_previous_job__.kt
    b
    2 replies · 2 participants
  • a

    adeln

    02/06/2019, 11:02 AM
    Hey folks, I have a question https://stackoverflow.com/q/54552056/1032286 would really appreciate if someone can help me with this
    g
    7 replies · 2 participants
  • z

    zokipirlo

    02/06/2019, 12:18 PM
    If I
    launch
    a coroutine where I call one long blocking method (some library in native code) on
    <http://Dispatcher.IO|Dispatcher.IO>
    , is it possible that this coroutine executes on a thread on which some other coroutine is running and will block execution of that other coroutine?
    s
    y
    7 replies · 3 participants
  • s

    streetsofboston

    02/06/2019, 6:30 PM
    Is it possible to listen to a
    ReceiveChannel
    to get notified when it is closed, either through an error or without one (just normally closed)?
    a
    l
    14 replies · 3 participants
  • m

    mp

    02/06/2019, 7:50 PM
    Is there a tidy way to wait for any of`n` coroutines to finish (don’t care which one finishes first, just give me the first one)
    l
    a
    6 replies · 3 participants
  • n

    niqo01

    02/07/2019, 12:01 AM
    Hello there, I am following the Kotlin coroutines documentation and I am at the chapter of "Confined vs unconfined dispatcher": https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html#unconfined-vs-confined-dispatcher I copy pasted the first sample code into Try kotlin website and I don't get the same result as described in the documentation:
    launch(Dispatchers.Unconfined) { // not confined -- will work with main thread
            println("Unconfined      : I'm working in thread ${Thread.currentThread().name}")
            delay(500)
            println("Unconfined      : After delay in thread ${Thread.currentThread().name}")
        }
        launch { // context of the parent, main runBlocking coroutine
            println("main runBlocking: I'm working in thread ${Thread.currentThread().name}")
            delay(1000)
            println("main runBlocking: After delay in thread ${Thread.currentThread().name}")
        }
    I get:
    Unconfined      : I'm working in thread main @coroutine#2
    main runBlocking: I'm working in thread main @coroutine#3
    Unconfined      : After delay in thread kotlinx.coroutines.DefaultExecutor @coroutine#2
    main runBlocking: After delay in thread main @coroutine#3
    Instead of:
    Unconfined      : I'm working in thread main
    main runBlocking: I'm working in thread main
    Unconfined      : After delay in thread kotlinx.coroutines.DefaultExecutor
    main runBlocking: After delay in thread main
    Any idea why ?
    b
    3 replies · 2 participants
  • a

    ansman

    02/07/2019, 2:25 AM
    I have a long running job that I would like to publish progress for. Currently the API looks like this:
    suspend fun performHeavyWork()
    Would it be advisable to use an actor for this case? The callee should be able to receive a progress value between 0-1 (or 0-100).
    o
    g
    +1
    14 replies · 4 participants
  • n

    Nikky

    02/07/2019, 2:25 AM
    i am dealing with a super slowed paged api, limited to a pagesize of 1000 currently i just reqest it concurrently and stop once the result size drops under the requested page size what would be a clean solution to request 10 pages at a time and mark which one results in less results than the requested pagesize ? i was thinking of having a fixedThreadpool process from a channel and the first one that finds the end will somehow trigger that no more jobs are being created.. but not sure how to do this and ofc its not actually guaranted that there is no shifting of data between the requests.. there might be entries added or removed 🤮
    g
    7 replies · 2 participants
  • e

    Edouard Goossens

    02/07/2019, 10:18 AM
    Hi all. The following function returns a channel that I later use with “consumeEach”. However, the receiver keeps getting COROUTINE_SUSPENDED. What am I not understanding/doing wrong?
    actual fun observe(): ReceiveChannel<DocumentSnapshot> {
            val channel = Channel<DocumentSnapshot>(Channel.CONFLATED)
            val removeListener = documentReference.onSnapshot({
                channel.offer(DocumentSnapshot(it))
            }, {
                channel.close(it)
            })
            channel.invokeOnClose { removeListener() }
            return channel
    }
    1 reply · 1 participant
  • j

    jkbbwr

    02/07/2019, 10:56 AM
    How would I make a coroutine suspend until an item is not in a set
    m
    n
    +1
    6 replies · 4 participants
  • w

    withoutclass

    02/07/2019, 4:18 PM
    actor, fixed thread pool, a channel with 2 listening coroutines
    a
    g
    31 replies · 3 participants
  • a

    ansman

    02/07/2019, 6:12 PM
    What’s the idiomatic way to share a job between multiple callers? I’ve done this now:
    val pendingJobs = Collections.synchronizedMap(mutableMapOf<String, Deferred<Stuff>>())
    
    suspend fun getStuff(key: String): Stuff = pendingJobs.computeIfAbsent(key, ::computeStuff)
    suspend fun computeStuff(key): Stuff = /* Long running operation */
    but that doesn’t feel like it’s the Kotlin way.
    s
    d
    12 replies · 3 participants
  • k

    kevinherron

    02/07/2019, 6:56 PM
    anybody having trouble setting breakpoints in suspend functions?
    g
    d
    +1
    13 replies · 4 participants
  • g

    groostav

    02/08/2019, 12:07 AM
    So, as a library author, if you choose to create some type
    MyWorkingThing: kotlinx.coroutines.Job
    , what kinds of things should you do with cancellation? In my case,
    MyWorkingThing
    acquires a resource that I would like to synchronize on the disposal of before letting the job hit the
    Compelted
    state. The
    Cancelling
    state seems to reflect this well: if you hit
    cancel()
    on a job, it goes
    cancelling
    while it attempts to clean up its resources. The problem is cleaning up those resources is itself a long-running operation, and I cant suspend something while its being cancelled because, well, its being cancelled. Should I just block? Should I just document
    MyWorkingThing
    with some docs to the effect of:
    hey, if you cancel a
    MyWorkingThing
    its going to launch some teardown jobs in global scope.
    l
    3 replies · 2 participants
  • d

    Dias

    02/08/2019, 3:31 PM
    deferred is marked as volatile and I only set it, so it should be thread safe(?)
    g
    5 replies · 2 participants
Powered by Linen
Title
d

Dias

02/08/2019, 3:31 PM
deferred is marked as volatile and I only set it, so it should be thread safe(?)
g

groostav

02/10/2019, 12:29 AM
You're asking that question from a very weak position. when using
kotlinx.coroutines
, its best to stay away from
volatile
,
java.util.concurrent
et al. I also suspect you're trying to use a deferred, which is fundamentally a one-shot value type, as the facade into a running process (which it is not).
So, I'm having a bit of trouble understanding your retry logic. Rather than using an abstraction that is a
var deferred
, which is having its value changed on restarts, how about you use a
Channel<String>
? a
ConflatedBroadcastChannel
might do what you want it to do.
https://gist.github.com/Groostav/c61c4df0eb5b272110fe1bd44d2cc705
d

Dias

02/11/2019, 9:28 AM
yeah your guess is right about using a deferred as facade of a process, it was an existing code that I was trying to improve, but looks like ConflatedBroadcastChannel is exactly what I need!
As far as I understood ConflatedBroadcastChannel keeps sending a value until it is replaced by another value?
View count: 7