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

    kevinherron

    12/14/2018, 4:02 AM
    can anyone explain why this prints an uncaught exception to the console after 5 seconds? if I don't cancelAndJoin() the job, it acts like I expect. but the exception escapes the
    GlobalScope.async
    if the job `await()`ing it was cancelled. https://gist.github.com/kevinherron/37155732ccd4c0587a69a9d86e16b448
    b
    • 2
    • 1
  • x

    xenoterracide

    12/14/2018, 5:35 AM
    what's the advantage of coroutines over jvm threads? in js do they work as workers? what happens when you compile to native?
    g
    • 2
    • 7
  • g

    gildor

    12/14/2018, 6:05 AM
    @ursus Moving discussion to coroutines, otherwise too many offoptic for this thread https://kotlinlang.slack.com/archives/C09222272/p1544765551091900?thread_ts=1544517238.067400&cid=C09222272
    • 1
    • 6
  • k

    kevinherron

    12/14/2018, 12:28 PM
    i've simplified, can anyone explain why this leads to an uncaught exception logged to console?
    fun main(args: Array<String>) {
        val job = SupervisorJob()
        val scope = CoroutineScope(job + Dispatchers.Default)
    
        val deferred = GlobalScope.async(Dispatchers.Default, start = CoroutineStart.LAZY) {
            delay(5000)
            throw Exception("boom")
        }
    
        scope.launch {
            try {
                deferred.await()
            } catch (e: Exception) {
                println("error awaiting: $e")
            }
        }
    
        runBlocking { job.cancelAndJoin() }
    
        Thread.sleep(10000)
    }
    e
    • 2
    • 18
  • d

    Dico

    12/14/2018, 3:35 PM
    So you're cancelling a coroutine that is waiting, and thus expecting no error to be logged when the exception is thrown
    k
    b
    • 3
    • 6
  • t

    Tristan Caron

    12/14/2018, 4:54 PM
    Hello, About the JS implementation of
    kotlinx.coroutines
    . What is the base? I suppose
    Deferred
    is internally using
    Promise
    , but what about
    Job
    ? Is it working with
    Worker
    ?
    g
    • 2
    • 12
  • m

    Michal Fudala

    12/16/2018, 11:39 AM
    How do I cancel long running operation when a couroutine is cancelled ? I know I can somehow use
    isActive
    , but here I would want to provide some kind of
    onCancelled
    callback. (here when I do cancel process is still present when doing
    ps aux
    )
    file.kt
    t
    u
    • 3
    • 5
  • d

    dave08

    12/16/2018, 3:09 PM
    Is there any way to get an exception that was caught in
    produce
    on the receiving end (apart from a sealed class, all I need is a Long progress value, and it's a pity to have to box/unbox them unecessarily)?
    m
    • 2
    • 7
  • d

    Dias

    12/17/2018, 10:31 AM
    I am reading coroutines keep and there is a line that doesn't make sense to me:
    It is a mix between a set and a map. Its elements have keys like in a map, but its keys are directly associated with elements, more like in a set.
    But sets don't have keys, do they? And maps have their keys directly associated with values? Am I reading it wrong?
    💯 2
    m
    • 2
    • 12
  • d

    dave08

    12/17/2018, 1:41 PM
    I have a callback receiving progress on downloading part of a file, I want to accumulate the progress of all the parts being downloaded to show progress in an Android app, do I really need that channel to send the results? Is there any better way to accumulate these results with a channel (maybe without the AtomicLong)?
    Untitled.kt
    g
    • 2
    • 4
  • n

    nil2l

    12/17/2018, 3:37 PM
    Is there something ready-to-use for Throttling (skip some events for a while and handle only last one)? 🤔
    m
    d
    +4
    • 7
    • 15
  • m

    Martin Devillers

    12/18/2018, 10:11 AM
    Do coroutines safely prevent memory leaks? I’d assume so, but if that’s the case I think that it would be a good idea to state it more explicitly in the documentation.
    Untitled.kt
    g
    e
    +3
    • 6
    • 37
  • m

    Martin Devillers

    12/18/2018, 3:13 PM
    Me again 🙂 This time I’m confused by some behavior involving
    withContext
    and
    CompletableDeferred
    .
    -.kt
    • 1
    • 4
  • a

    Alexander Romanov

    12/18/2018, 4:11 PM
    val queueListener = launch {
            while (isActive) {
                // do something
            }
        }
    
        Runtime.getRuntime().addShutdownHook(Thread {
            <http://logger.info|logger.info> { "Cancellation requested" }
            queueListener.cancel()
        })
    
        queueListener.join()
        <http://logger.info|logger.info> { "Exiting program" }
    why would “Exiting program” never show up? are there any other way to do it? I am also considering channel that sends some cancellation event. But what wold be the better way to handle this?
    s
    • 2
    • 4
  • d

    dave08

    12/18/2018, 5:40 PM
    Are
    actor
    send channels automatically closed at the end of the
    coroutineScope { }
    that they're declared in?
    g
    • 2
    • 3
  • z

    zak.taccardi

    12/18/2018, 5:41 PM
    I assume so
    🇳🇴 2
    u
    • 2
    • 1
  • v

    Vsevolod Tolstopyatov [JB]

    12/18/2018, 8:23 PM
    📣 📣 📣 I am happy to announce
    kotlinx.coroutines
    1.1.0-alpha! This is a major release with two new modules, a lot of improvements in testability and debuggability, various performance improvements and bug fixes. Changelog: *
    kotlinx-coroutines-test
    module with testable
    Dispatchers.Main
    *
    kotlinx-coroutines-debug
    module with debug agent to track and debug active coroutines * Stacktrace recovery mechanism that provides additional coroutine-based stacktraces in exceptions (enabled in debug mode) *
    MainScope
    and
    CoroutineScope.cancel
    methods for simpler integration with structured concurrency *
    CancellableContinuation
    race between
    resumeWithException
    and
    cancel
    is now not treated as an uncaught exception *
    Dispatchers.Default
    CPU consumption in idle state is reduced *
    JavaFx
    dispatcher initialization bug fixed Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.1.0-alpha
    🎉 33
    u
    c
    +3
    • 6
    • 9
  • p

    pawelbochenski

    12/19/2018, 7:18 AM
    Hi, I have method with a callback, that will be called more then once. how to wrap it into coroutine?
    b
    d
    +2
    • 5
    • 21
  • s

    sashjakk

    12/19/2018, 1:59 PM
    Hey, have a question about `Job#invokeOnCompletion`… Is it true that after calling
    cancelAndJoin
    completion block is not guaranteed to be executed right after
    cancelAndJoin
    have completed? Tried to add some logging to see jobs actually finished
    v
    • 2
    • 3
  • z

    zak.taccardi

    12/19/2018, 5:33 PM
    is there a built in construct for a suspending
    lazy
    ?
    g
    • 2
    • 9
  • s

    Sam

    12/19/2018, 9:51 PM
    Does any one have unit test recommendation for testing coroutine launched from Android's ViewModel scope? I'm able to pass a Unconfined dispatcher from unit tests to work around the Main looper uninitialized case. However, mockito verify fails as expected call and actual call differs in continuation
    s
    m
    • 3
    • 2
  • z

    zak.taccardi

    12/19/2018, 9:52 PM
    inject your dispatcher into the `ViewModel`’s constructor
    s
    • 2
    • 1
  • z

    zak.taccardi

    12/19/2018, 9:56 PM
    thread here
    s
    s
    d
    • 4
    • 50
  • j

    joao.alves

    12/19/2018, 10:12 PM
    I’m a bit confused here. I’m following this talk from Christina Lee from Droidcon around coroutines and trying to migrate my sample app from Rx following it. My question is, if I define the coroutineContext using the Main dispatcher by default, when I call
    launch {}
    am I not running the code inside on the main thread?
    Can_someone_clarify_something_for_me_.kt
    m
    • 2
    • 1
  • j

    joao.alves

    12/19/2018, 10:17 PM
    ok she probably missed it then and it was confusing me a bit, thanks for the help
    m
    • 2
    • 2
  • j

    joao.alves

    12/19/2018, 10:21 PM
    that’s the thing I don’t. If I remove all the
    withContext
    and leave the
    launch
    as it is, and with the base context defined as Main + job it works just fine
    d
    a
    • 3
    • 4
  • b

    bdawg.io

    12/20/2018, 2:25 AM
    Is there a type of channel that gives you an exclusive "lease" to an element until either a) the worker acknowledges it should be removed or b) a time out is reached that returns the element back to the front of the channel? (similar to Amazon's SQS)
    d
    • 2
    • 1
  • s

    spierce7

    12/20/2018, 5:19 AM
    @elizarov Is it possible to use the coroutine context to hold other information, such as a database connection that follows a request through the server? I can think of several instances where it would be nice to to use a coroutine context to intrinsically hold certain pieces of data to follow an async request.
    g
    d
    • 3
    • 83
  • t

    Tolriq

    12/20/2018, 9:01 AM
    What is the proper way in a simple suspend function to check if it's running inside a job and if that job is cancelled?
    g
    • 2
    • 29
  • d

    dave08

    12/20/2018, 1:15 PM
    Is there a way to retrieve the android Handler from coroutineContext?
    g
    • 2
    • 8
Powered by Linen
Title
d

dave08

12/20/2018, 1:15 PM
Is there a way to retrieve the android Handler from coroutineContext?
g

gildor

12/20/2018, 1:50 PM
You can get dispatcher but there is no public method to get handler from dispatcher
coroutineContext[Dispatcher]
d

dave08

12/20/2018, 2:13 PM
Oh... I'm trying to adapt a library's callbacks to coroutines, and I need to pass it a handler in
suspendCoroutine { }
so that it can run on it... 😕
g

gildor

12/20/2018, 3:53 PM
I’m not sure about your case. Can you give little bit more context
Just create a handler or pass it to await function, why do you need Handler from coroutineContext? Because coroutineContext may have no any dispatcher or no HandlerDispatcher
d

dave08

12/20/2018, 6:00 PM
I need to run a library on my android service's Handler, but it would be a plus if I could have it run on the caller CoroutineScope's dispatcher handler?
g

gildor

12/20/2018, 11:26 PM
But what if caller doesn't use dispatcher with handler
Why not just let user of API pass handler if it's important
View count: 6