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

    Allan Wang

    09/27/2018, 8:49 PM
    Do flyweight patterns exist in coroutines? For example, let's say I have 5 suspend methods that require a parameter, which can also be retrieved by a suspend method. If I call two of them simultaneously, is there a way for me to have them wait on the same suspension? One way of doing this would be to keep a map of keys to deferred values, where I assume that calling await twice will only run the logic once. Is there a better way of achieving that?
    b
    • 2
    • 2
  • b

    bj0

    09/27/2018, 8:51 PM
    caching the value?
    a
    • 2
    • 2
  • m

    muralimohan962

    09/28/2018, 6:02 AM
    Can anyone point me to some comprehensive resources on how coroutines are implemented under the hood?
    i
    z
    • 3
    • 2
  • o

    orangy

    09/28/2018, 6:08 AM
    https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/coroutines-guide.md
    m
    d
    • 3
    • 4
  • d

    Darshan Mistry

    09/28/2018, 7:10 AM
    Hello all, Any good article or video to learn coroutine. Currently, I am referring github documentation (https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/basics.md)
    s
    g
    • 3
    • 3
  • s

    spand

    09/28/2018, 9:01 AM
    Has kotlin versions of Guardedby, Immutable, NotThreadSafe and ThreadSafe annotations been considered ? With associated compiler / ide support that is ?
    e
    • 2
    • 6
  • l

    louiscad

    09/28/2018, 1:55 PM
    Hi, am I right that there's no way to distinguish whether a
    CancellationException
    is caused by a function call or by the cancellation of the coroutine scope? I'd like to handle cancellation caused by a function call without stopping suspending iteration, unless the whole scope is cancelled (because the Activity is destroyed)
    :thread-please: 1
    e
    • 2
    • 5
  • p

    Paul Woitaschek

    09/28/2018, 2:41 PM
    Now with kotlinx.coroutines 0.27.0 I receive the following proguard warning:
    l
    • 2
    • 1
  • v

    Vsevolod Tolstopyatov [JB]

    09/28/2018, 5:49 PM
    📣 📣 📣
    kotlinx.coroutines
    version
    0.30.0
    . We are happy to announce the last release for Kotlin 1.2.70 and the last
    0.x.x
    release. The next release will be 1.0.0-RC for Kotlin 1.3-RC and all deprecated API will be removed. Changelist: * [Major]
    async
    and async-like builders cancel parent on failure, making parallel decomposition completely exception-safe. No more unnecessary
    awaitAll
    in structured concurrency! * [Major] Coroutine scheduler is used for
    Dispatchers.Default
    instead of deprecated
    CommonPool
    . * Supervisor job and supervisor scope for more controlled cancellation of coroutines hierarchies. *
    Job()
    with parent now also cancels parent on failure consistently with other scopes. * Various bug fixes and improvements. See the full changelog here: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/0.30.0. To properly prepare your application to 1.0.0 release, do the following steps: 1) Update
    kotlinx.coroutines
    to
    0.30.0
    version. 2) Inspect compiler warnings about deprecated API and migrate it to a proposed alternative. Most of deprecated API has a corresponding replacement which can be applied from IDEA with quickfix. 3) Update Kotlin version to 1.3-RC and
    kotlinx.coroutines
    to
    0.30.0-eap13
    . 4) Update
    kotlinx.coroutines
    to
    1.0.0
    when it’s released 🙂 Compatibility and migration policy: https://github.com/Kotlin/kotlinx.coroutines/blob/master/COMPATIBILITY.md
    🎉 14
    c
    l
    e
    • 4
    • 5
  • a

    apomelov

    09/28/2018, 6:10 PM
    Hi. I'm trying to understand coroutines a bit deeply, but missing some materials for the very beginning. I heard that coroutines are much "cheaper" than threads. Sounds nice. Does it mean that I shouldn't use threads anymore? Each time I want to run some parallel computation I use coroutines instead of threads now?
    l
    • 2
    • 7
  • a

    alex009

    09/29/2018, 1:57 AM
    hello! after update multiplatform (ios & android) module to kotlin 1.3 RC with coroutines to 0.26.1-rc-conf2 i got on ios error IncorrectDereferenceException, stacktrace in thread
    • 1
    • 3
  • e

    elizarov

    09/29/2018, 3:57 PM
    📣
    kotlinx.coroutines
    version
    0.30.0-eap13
    for Kotlin
    1.3.0-rc-57
    (can be used from
    1.3.0-rc-116
    , too) & Kotlin/Native
    0.9.2
    a
    • 2
    • 3
  • t

    thevery

    09/29/2018, 10:55 PM
    With new SC, is there any changes in
    withContext
    vs
    async
    policy or it is ok to continue using
    withContext
    ?
    CoroutineScope
    sample uses
    async
    , not `withContext`: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/index.html
    g
    k
    e
    • 4
    • 5
  • l

    louiscad

    09/30/2018, 12:28 PM
    Does calling
    coroutineContext.cancel()
    for a
    suspend fun
    immediately throws
    CancellationException
    to interrupt the execution of the function, or should I call
    yield()
    afterwards?
    e
    • 2
    • 1
  • p

    pakoito

    09/30/2018, 12:35 PM
    suspended functions run synchronously until the first suspension point
    r
    • 2
    • 3
  • m

    mayojava

    09/30/2018, 4:45 PM
    are there any major difference between
    <http://Dispatchers.IO|Dispatchers.IO>
    and
    Dispatchers.DEFAULT
    that one needs to know about
    d
    e
    • 3
    • 3
  • v

    vaskir

    10/01/2018, 11:00 AM
    Is it possible to run an
    actor
    on a dedicated Dispatcher (e.g. the IO one)?
    e
    • 2
    • 3
  • v

    vaskir

    10/01/2018, 11:31 AM
    I cannot find https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/exception-handling.md#supervision-job in
    0.26.1-eap13
    j
    • 2
    • 4
  • v

    vaskir

    10/01/2018, 12:02 PM
    Another example is a server process that spawns several children jobs and needs to supervise their execution, tracking their failures and restarting just those children jobs that had failed.
    I cannot get my head around how to restart a children (say, an
    actor
    ) from inside a
    CoroutineExceptionHandler
    😞 What I really need is just restarting strategy a-la Akka.
    fun CoroutineScope.worker(ctx: CoroutineContext) = actor<Int>(ctx) {
        for (msg in channel) {
            println("got $msg")
            if (msg == 2) throw Exception("it's $msg and we are failing")
        }
    }
    
    GlobalScope.launch {
        val supervisor = SupervisorJob()
        var actor: SendChannel<Int>?
    
        val handler = CoroutineExceptionHandler { _, _ ->
            {
                actor = worker(coroutineContext + supervisor + handler) // error: handler is not defined
            }
        }
    
        actor = worker(coroutineContext + supervisor + handler)
    
        for (msg in 1..5)
            actor?.send(msg)
    }
    e
    j
    • 3
    • 14
  • m

    miguelsesma

    10/01/2018, 12:40 PM
    Any idea?
    v
    • 2
    • 4
  • e

    elizarov

    10/01/2018, 1:13 PM
    @minivac The proper and idiomatic way is to never use
    Deferred
    as your return type. Write a suspending function instead:
    suspend fun doSomething(param: Int): Something {
       code ...
    }
    See how much more concise it is!
    n
    j
    • 3
    • 3
  • l

    louiscad

    10/01/2018, 3:18 PM
    Hi, is there a way to cancel/close a
    ReceiveChannel
    without clearing its buffer? I'd like to stop an underlying items generation, and get what was processed so far as a list. I used
    cancel()
    in the past, but it seems it now clears the buffer, and I'm looking for an alternative.
    e
    • 2
    • 2
  • u

    uhe

    10/01/2018, 3:35 PM
    I'm a bit confused by the new scoping mechanism. I'm trying to migrate some coroutine-based code and stumbled upon this:
    @Deprecated("No replacement. Group child in a coroutineScope { } block to wait for them")
    public suspend fun Job.joinChildren()
    However, I don't see how to "group child in a coroutineScope". For example:
    val networkContext = <http://Dispatchers.IO|Dispatchers.IO>
    val networkJob = Job()
    
    private fun onNetworkContext(block: suspend CoroutineScope.() -> Unit) =
        GlobalScope.launch(networkContext + networkJob, block = block)
    
    // invoked from another coroutine:
    suspend fun abortAndRetry() {
        networkJob.cancelChildren()
        // how do I replace this properly?
        networkJob.joinChildren()
       // retry ...
     }
    j
    e
    • 3
    • 10
  • n

    nerses

    10/01/2018, 8:15 PM
    repeat(1000) { loadAndCombine() }
    will take 1000 seconds
    repeat(1000) { launch { loadAndCombine() }}
    will take 1 second my question is whether wrapping it with
    launch
    is the “correct” way of doing this
    g
    • 2
    • 3
  • f

    fabiocollini

    10/02/2018, 6:33 AM
    hi everyone, I am trying to use the
    produce
    method to create a channel inside a suspending method but I have some problems. I have a different behaviour defining my method as
    CoroutineScope
    extension method and using
    coroutineScope
    inside a suspending method. These are the two versions:
    private fun CoroutineScope.produceExtension(): ReceiveChannel<Int> = produce {
        send(1)
        send(2)
        send(3)
    }
    
    private suspend fun produceCoroutineScope(): ReceiveChannel<Int> = coroutineScope {
        produce {
            send(1)
            send(2)
            send(3)
        }
    }
    `
    Using the second method I am not able to use the channel (the method never ends), I have already opened an issue with the complete code here https://github.com/Kotlin/kotlinx.coroutines/issues/645 Am I doing something wrong? Should the two methods be equivalent?
    g
    k
    • 3
    • 21
  • v

    Vsevolod Tolstopyatov [JB]

    10/02/2018, 1:59 PM
    📣 📣 📣
    kotlinx.coroutines
    version
    0.30.1
    . This a maintenance release. Main change is that Android
    Main
    dispatcher is now available as
    Dispatchers.Main
    . It fixes issue with Android Studio (#626) and allows users to safely migrate to
    0.30.1
    without any tooling issues. Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/0.30.1
    :android: 3
    🎉 5
    ❤️ 1
    p
    • 2
    • 3
  • i

    Ian

    10/02/2018, 5:41 PM
    Trying to use the latest coroutines in the 1.3 EAP, but I keep getting this error on a call to `runBlocking`: https://slack-files.com/T09229ZC6-FD51JHCQZ-7d48808590
    l
    • 2
    • 1
  • i

    Ian

    10/02/2018, 5:44 PM
    From my reading, it’s due to SuccessOrFailure changing to something else in the EAP, but I’m not sure how to fix it. Should I be using something other than
    runBlocking { }
    now?
    e
    • 2
    • 1
  • h

    Hamza

    10/03/2018, 3:28 AM
    when i have this code:
    launch {
    ...
    }
    is this async? because i want to have some stuff done async, and then after the async, i want to go back to the main thread and call a sync function
    s
    u
    • 3
    • 20
  • m

    mayojava

    10/03/2018, 6:59 AM
    fun main(args: Array<String>) = runBlocking<Unit> {
        try {
            failedConcurrentSum()
        } catch(e: ArithmeticException) {
            println("Computation failed with ArithmeticException")
        }
    }
    
    suspend fun failedConcurrentSum(): Int = coroutineScope {
        val one = async<Int> { 
            try {
                delay(Long.MAX_VALUE) // Emulates very long computation
                42
            } finally {
                println("First child was cancelled")
            }
        }
        val two = async<Int> { 
            println("Second child throws an exception")
            throw ArithmeticException()
        }
            one.await() + two.await()
    }
    it doesnt seem to work for me. The parent coroutine still blocks waiting for the first
    async
    after the second threw the exception
    v
    d
    • 3
    • 4
Powered by Linen
Title
m

mayojava

10/03/2018, 6:59 AM
fun main(args: Array<String>) = runBlocking<Unit> {
    try {
        failedConcurrentSum()
    } catch(e: ArithmeticException) {
        println("Computation failed with ArithmeticException")
    }
}

suspend fun failedConcurrentSum(): Int = coroutineScope {
    val one = async<Int> { 
        try {
            delay(Long.MAX_VALUE) // Emulates very long computation
            42
        } finally {
            println("First child was cancelled")
        }
    }
    val two = async<Int> { 
        println("Second child throws an exception")
        throw ArithmeticException()
    }
        one.await() + two.await()
}
it doesnt seem to work for me. The parent coroutine still blocks waiting for the first
async
after the second threw the exception
v

Vsevolod Tolstopyatov [JB]

10/03/2018, 1:18 PM
Have you updated your coroutines version to 0.30.1?
d

Dico

10/03/2018, 2:57 PM
The reason is that the
two
coroutine doesn't throw its exception until you call
two.await()
which doesn't occur until
one.await()
returns.
If the exception thrown by
two
is supposed to cancel the parent before
await()
is called then I guess I don't know.
v

Vsevolod Tolstopyatov [JB]

10/03/2018, 10:03 PM
@Dico this behaviour was changed in the latest realese
➕ 1
View count: 5