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

    Harun

    02/09/2019, 3:30 PM
    Is it okay when you pass coroutine scope in the constructor parameters for classes without lifecycles?For example a paged list data source then, use factory class to add the parameters to the data source class, then handle the lifecycle of the coroutine in a view model or fragment/activity
    s
    • 2
    • 2
  • f

    frellan

    02/09/2019, 4:05 PM
    Hello, I have a question. I want to perform a simple background job using coroutines. Currently I have an
    object
    that does stuff and writes to a status object that I can then read to know the state of the job (like how many items are processed etc). This is obviously crap because I currently block the entire server. I now want to redo this the right way. I use
    launch
    since the job doesnt return anything, it just does stuff. I know I can ask that job
    isActive()
    and stuff like that but how can I ask access that jobs memory, like shared memory? I just want to ask how many items it has processed etc so I can show that in my frontend.
    z
    y
    • 3
    • 7
  • b

    Bernhard

    02/10/2019, 9:57 PM
    I found the current one pretty hard to grasp when I looked up how to do 4 things in parallel and collect their results
    r
    • 2
    • 2
  • e

    elizarov

    02/11/2019, 6:52 AM
    Yes, it should be improved. It is hard to get started using existing documentation. You basically need to understand all of it (a lot) to get a good grasp of various patterns and practices. However, it is not that straightforward on how exactly to improve it. The current docs assumes you have have thread/async programming experience and builds upon that (for example,
    GlobalScope.launch
    is what you typically do nowadays), showing how to improve your code with structured concurrency a bit later. If we jump right away into the structured concurrency, as you suggest, then there is a risk it’ll look totally like magic for readers, so that people with a prior threads/async experience will have no way to bridge it to their existing knowledge.
    👍 12
    p
    • 2
    • 2
  • a

    antonis

    02/11/2019, 9:50 AM
    I wrote a Coroutines intro a couple of months ago if that’s of any help https://antonis.me/2018/12/12/an-introduction-to-kotlin-coroutines/ Part of this was inspired by @elizarov talk on kotlin conf last year
    👍 4
    :tnx: 1
    g
    d
    • 3
    • 2
  • c

    ck

    02/11/2019, 11:14 AM
    Hi, what is the recommended way on Android to handle exceptions that occur inside
    GlobalScope.launch
    ? A
    CoroutineExceptionHandler
    ?
    g
    d
    a
    • 4
    • 10
  • s

    svenjacobs

    02/11/2019, 11:48 AM
    Hi, I want to wrap a legacy listener that fires multiple times into a
    Channel
    . However I'm a bit lost here. Here's the simplified pseudo code:
    suspend fun Query.onSnapshotAsync(scope: CoroutineScope) =
        scope.produce {
            addSnapshotListener { snapshot ->
                send(snapshot.documents)
            }
        }
    however at
    send()
    it gives me the error
    suspension functions can be called only within coroutine body
    . Usually I wrap legacy callbacks with
    suspendCoroutine
    but in this case this is not possible since the listener fires multiple times but a Continuation can only be resumed once. What is the best practice here?
    d
    b
    • 3
    • 29
  • t

    tseisel

    02/11/2019, 4:40 PM
    What is the recommanded way to test suspending functions that are members of a class ? In the code below my test function is suspended indefinitely and the
    assertThat
    statement is never reached. Why ?
    Sans_titre.kt
    d
    • 2
    • 3
  • k

    kenkyee

    02/11/2019, 10:15 PM
    What happened to GlobalScope.future{} ? I thought that was the way to interop w/ Java so Java can call a coroutine?
    b
    • 2
    • 3
  • v

    vngantk

    02/12/2019, 3:16 AM
    I am still struggling with some basic concepts of coroutines. What is the purpose of having CoroutineScope when there is already CoroutineContext?
    g
    s
    d
    • 4
    • 31
  • m

    mp

    02/12/2019, 2:02 PM
    Is there a coroutine-flavored equivalent of a j.u.c.semaphore? I have a known amount of work to send over the network, and it can only be handled of batches of at most 10, so I’d like to simply spawn a zillion coroutines, each of which will handle 10 items, but to avoid overwhelming the other end I’d like to limit the concurrency ala a semaphore.
    a
    m
    b
    • 4
    • 37
  • a

    Alessandro Diaferia

    02/12/2019, 3:49 PM
    can you guys advise what’s an idiomatic way of handling a suspending initialization? Let’s say my class exposes a
    search
    function and this function depends on a series of initialization steps that the instance has to perform before being able to actually search and return results. How would you handle this using coroutines? Would you have an
    initialize
    function that returns a
    Job
    or would you simply mark
    search
    as
    suspend
    and “hide” the suspension as an implementation detail waiting internally for the initialization job to complete? Or would you tackle this issue in a completely different way?
    w
    d
    d
    • 4
    • 3
  • n

    nicholasnet

    02/12/2019, 9:20 PM
    I am just trying to learn Kotlin coroutine. This is what I have so far. I am trying to load several data using Kotlin to speed things up. However, I am not sure whether this is the right approach or not in terms of error handling. Does it leaks memory if any of the coroutine fails? Is there a better way to do this?
    snippet_kt.kt
    d
    • 2
    • 4
  • k

    kawmra

    02/13/2019, 8:33 AM
    Hi. I have some questions about the coroutine scope. What is the difference between the scope created with
    coroutineScope()
    and the scope created with
    launch()
    or
    async()
    ? Both
    coroutineScope()
    and
    launch()
    create new instance of CoroutineScope (maybe AbstractCoroutine), the both do create new coroutine scope, right? If the coroutine throws an error, the parent coroutine will be canceled too. But if the coroutine inside of the scope created by
    coroutineScope()
    throws an error, the coroutine that called the
    coroutineScope()
    will not be canceled. Why? Is it that the coroutine created by
    coroutineScope()
    is not a child of the coroutine that did call
    coroutineScope()
    ? Or there is something different between the two scopes? This very confuses me to understand what the coroutine scope is.
    g
    d
    • 3
    • 17
  • c

    ck

    02/13/2019, 1:26 PM
    Has anyone had troubles with ProGuard after adding Coroutines? After adding the Coroutines dependency I am getting this ProGuard error message when building:
    Shrinking...
    
    Removing unused program classes and class elements...
      Original number of program classes: 9596
      Final number of program classes:    9596
    
    Obfuscating...
    
    Printing mapping to [/Users/jenkins/Public/workspace/Android-App_ck_ANDROID-313/app/build/outputs/mapping/playStore/release/mapping.txt]...
    
    Warning: Exception while processing task java.io.IOException: java.util.EmptyStackException
    Thread(Tasks limiter_1): destruction
    
    > Task :app:transformClassesAndResourcesWithProguardForPlayStoreRelease FAILED
    FAILURE: Build failed with an exception.
    l
    • 2
    • 3
  • a

    aaverin

    02/13/2019, 1:38 PM
    Is there documentation on how to handle errors properly with channels? https://kotlinlang.org/docs/reference/coroutines/exception-handling.html doesn’t mention channels, and Channel docs has nothing on error handling
    l
    • 2
    • 1
  • j

    Juan Rada

    02/13/2019, 5:22 PM
    Hey guys, do you know any library that provide coroutine friendly (or async) high level api for file system operations, like copy file, save file. Something like an async version of apache
    commons-io
    ?
    g
    • 2
    • 2
  • s

    sitepodmatt

    02/14/2019, 4:23 AM
    -.txt
    g
    • 2
    • 9
  • s

    sitepodmatt

    02/14/2019, 4:24 AM
    Other than the obvious of passing it in as a parameter?
    g
    • 2
    • 6
  • s

    sitepodmatt

    02/14/2019, 6:13 AM
    producer_kt.kt
    g
    t
    • 3
    • 10
  • a

    Alessandro Diaferia

    02/14/2019, 3:09 PM
    Is there some sort of
    dispatch_once
    in the Kotlin Coroutine world?
    m
    a
    • 3
    • 8
  • i

    igor.wojda

    02/14/2019, 4:00 PM
    Hey I am getting
    JobCancellationException
    and I am not sure what is the reason. My only hypothesis is that I am starting and canceling multiple times function that is in suspended state 🤔 but honestly I am not sure… Can somebody throw more light on this? What is the reason for throwing this exception?
    l
    b
    • 3
    • 8
  • m

    minisu

    02/15/2019, 8:53 AM
    I have a function that divide and conquers a CPU-intensive task using coroutines. I want to test that it actually runs concurrently in a unit test. If I were using threads, I would have called the function tasks that awaited a common
    CyclicBarrier
    . How can I achieve something similar with coroutines?
    e
    • 2
    • 8
  • s

    spierce7

    02/15/2019, 2:34 PM
    I've setup Coroutine Scopes inside our Presenter class, where every child coroutine has one of 2 parent coroutines. I'm seeing some really odd behavior around `CoroutineExceptionHandler`s, where after we receive a single exception, every child coroutine immediately fails with the same exception again. Code snippets on thread.
    g
    u
    +2
    • 5
    • 34
  • j

    jivimberg

    02/15/2019, 4:20 PM
    What’s the best way of spawning children coroutines that do not propagate cancellation upwards. I don’t want to wait for completion and don’t care about canceling either. a) use a dummy Supervisor b) use GlobalScope.launch c) register a CoroutineExceptionHandler on the launch builder
    a
    e
    • 3
    • 9
  • s

    Sam

    02/15/2019, 10:00 PM
    Is it possible to set multiple CompletionHandler on a job?
    z
    b
    • 3
    • 17
  • z

    zak.taccardi

    02/15/2019, 10:14 PM
    Can a project that uses stable coroutines (
    1.1.1
    ) include a library that uses experimental coroutines (
    0.30.2
    )?
    b
    l
    e
    • 4
    • 16
  • a

    addamsson

    02/15/2019, 11:08 PM
    How concerned should I be because of this? https://www.reddit.com/r/Kotlin/comments/ar29yj/coroutines_cause_memory_leaks/
    o
    g
    +2
    • 5
    • 10
  • s

    sitepodmatt

    02/16/2019, 4:18 AM
    I want to register some information to flow along a chain of suspending method calls. Kind of like putting something in thread local storage when using a thread request e.g. tls["workingOn"] = "transforming quote #102345 to order". we've used something like this with nodejs before (https://github.com/vicanso/async-local-storage)
    g
    • 2
    • 2
  • c

    camdenorrb

    02/17/2019, 3:51 PM
    How do I use the Main dispatcher if my platform isn't Android?
    Exception_for_Main_dispatcher.kt
    e
    d
    • 3
    • 24
Powered by Linen
Title
c

camdenorrb

02/17/2019, 3:51 PM
How do I use the Main dispatcher if my platform isn't Android?
Exception_for_Main_dispatcher.kt
e

elizarov

02/17/2019, 3:59 PM
What's your UI framework?
c

camdenorrb

02/17/2019, 3:59 PM
I'm not using a UI
e

elizarov

02/17/2019, 3:59 PM
Then you don't have Main dispatcher.
(nor need one)
c

camdenorrb

02/17/2019, 3:59 PM
:C
Concurrent modification issues tho
e

elizarov

02/17/2019, 4:00 PM
Don't share mutable state. No issues
(don't make mistake UI frameworks do)
c

camdenorrb

02/17/2019, 4:00 PM
I'm just adding something to my eventbus
e

elizarov

02/17/2019, 4:01 PM
Isn't your eventbus thread-safe?
c

camdenorrb

02/17/2019, 4:01 PM
Ummmm, not currently lol
e

elizarov

02/17/2019, 4:01 PM
That's a bad event bus
c

camdenorrb

02/17/2019, 4:01 PM
;-;
e

elizarov

02/17/2019, 4:02 PM
Reading this might give you some ideas: http://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html
c

camdenorrb

02/17/2019, 4:02 PM
Thank you :3
Unfortunately after giving it a read, I don't think it helped me very much idea wise. The only thing I got that seems useful is Mutex for the situation I have run in. Anything else I can read @elizarov?
e

elizarov

02/17/2019, 4:43 PM
It really depends on what you are trying to achieve
c

camdenorrb

02/17/2019, 4:43 PM
I want to add multithreading/coroutine support to my eventbus
Which at the moment, just seems to be an issue with concurrently adding a value to the list
e

elizarov

02/17/2019, 4:44 PM
You might want to learn more about concurrency, first. "Java Concurrency in Practice" is a good book I can recommend.
c

camdenorrb

02/17/2019, 4:45 PM
Alright
e

elizarov

02/17/2019, 4:45 PM
As for coroutines, the easiest thing (that would not require any sharing of mutable state) is to represent your eventbus as an actor, that is confine all its operations to a single coroutine.
c

camdenorrb

02/17/2019, 4:46 PM
Ooo, alright. I'll read up on actors :3
d

dewildte

02/18/2019, 6:03 PM
@elizarov Do you suggest using actor coroutines as the event bus for a multiplatform application?
View count: 5