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

    11/25/2018, 9:19 AM
    message has been deleted
    d
    • 2
    • 2
  • l

    louiscad

    11/25/2018, 2:11 PM
    Hi all, do you think such a class should be in kotlinx.coroutines?
    import kotlinx.coroutines.CoroutineDispatcher
    import kotlinx.coroutines.Dispatchers
    import kotlinx.coroutines.withContext
    
    open class SuspendLazy<out T>(
        private val dispatcher: CoroutineDispatcher = Dispatchers.Default,
        initializer: () -> T
    ) {
        private val lazyValue = lazy(initializer)
        suspend operator fun invoke(): T = with(lazyValue) {
            if (isInitialized()) value else withContext(dispatcher) { value }
        }
    }
    b
    • 2
    • 4
  • t

    Tolriq

    11/25/2018, 2:59 PM
    Opening a new thread as I'm lost as finding the cause 😞 Using https://gist.github.com/Tolriq/dcbdc62c0e29d3b321034e990c3c85ce I have some crashes that are properly handled that are thrown by coroutines somewhere. I'm using the correct workaround 1 from https://github.com/Kotlin/kotlinx.coroutines/issues/830 So I suppose there's another place causing coroutines to throw the original unwrapped exception, but I can't find where 😞 I've tried to add a CoroutineExceptionHandler to the scope and exceptions are still thrown 😞 My only remaining guess would be that https://gist.github.com/Tolriq/dcbdc62c0e29d3b321034e990c3c85ce#file-okhttpworkerpool-kt-L70 there's something to do with CompletableDeferred and cancellation but can't find anything about that.
    p
    • 2
    • 1
  • a

    Alexey Pushkarev

    11/25/2018, 9:01 PM
    Hi everyone! Could someone please explain me why I can't call one suspend function inside another ?
    d
    d
    +2
    • 5
    • 27
  • a

    asad.awadia

    11/26/2018, 2:33 AM
    Is getting a key from redis considered a blocking call? Should it be wrapped in a
    withContext
    ?
    b
    • 2
    • 1
  • p

    Paul Woitaschek

    11/26/2018, 9:30 AM
    I have this function where I'm counting down dates. Now line 5 is suspending. The compiler warns me that it can only be called from within a coroutine body
    d
    g
    b
    • 4
    • 7
  • m

    mersan

    11/26/2018, 10:16 AM
    any way to not let IntelliJ get stuck when you try to decompile the Kotlin bytecode when there are coroutines used in the code?
    g
    • 2
    • 2
  • s

    Sam

    11/26/2018, 2:34 PM
    Is there a way to iterate over coroutineContext?
    g
    • 2
    • 2
  • o

    Orfeo Ciano

    11/26/2018, 3:26 PM
    Quick one: do you have any github repo with examples, good patterns, antipatterns for structured concurrency on Android???
    👍 3
    p
    • 2
    • 1
  • a

    asad.awadia

    11/26/2018, 3:56 PM
    If I use
    suspendCoroutine
    to wrap an async callback into a suspend function - which dispatcher does it use to run on? The same dispatcher that called it?
    👍 1
    z
    • 2
    • 1
  • s

    Sam

    11/26/2018, 7:58 PM
    How do i create a class implementing a suspend block?
    class LambdaClass : suspend () -> Unit {
    
        override fun invoke() {
            // do something
        }
    
    }
    z
    g
    b
    • 4
    • 12
  • m

    mersan

    11/26/2018, 10:47 PM
    I'll be giving a small introduction into coroutines at the work, any modifications or additions on this?
    -.md
    👍 2
    o
    • 2
    • 4
  • a

    asad.awadia

    11/27/2018, 12:49 AM
    How to
    await
    for completion of a suspending function that wraps a blocking call with
    withContext
    b
    g
    l
    • 4
    • 38
  • a

    Andrew Gazelka

    11/27/2018, 1:52 PM
    My coroutine approach for calculating prime numbers is slower (by about 700ms... total = 6700ms) , even when grouping multiple prime calculations. Any idea why or how I can make this faster? https://gist.github.com/andrewgazelka/977ade9862f7fd6fff686b6bdc1db70c
    g
    • 2
    • 1
  • o

    oshai

    11/27/2018, 2:00 PM
    I am having an issue with 1.0.1:
    java.lang.NoClassDefFoundError: kotlinx/coroutines/SupervisorJobImpl
    l
    c
    g
    • 4
    • 13
  • s

    Sam

    11/27/2018, 10:49 PM
    What am i missing here? handler is not invoked
    fun main( args : Array<String> ) {
    
        val handler = CoroutineExceptionHandler { _, throwable -> println( "Handled $throwable" ) }
    
        runBlocking(handler) {
    
            launch {
                println( "Handler is ${coroutineContext[CoroutineExceptionHandler]}" )
                delay( 1000)
                println( "first task" )
                throw UnsupportedOperationException()
            }
    
        }
    
    }
    a
    g
    • 3
    • 10
  • s

    spand

    11/28/2018, 8:19 AM
    If I use the pattern of using a
    Job()
    as an explicit lifecycle as mentioned here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/coroutine-context-and-dispatchers.md#cancellation-via-explicit-job Is installing a
    CoroutineExceptionHandler
    the only way to handle exceptions in the lifecycle ?
    g
    t
    • 3
    • 14
  • t

    Tolriq

    11/28/2018, 11:16 AM
    Just a quick question about what is better and differences between GlobalScope and withContext(NonCancellable) on Android Is there any advantage / problem with one of those functions? Typical use case would be using proper scoped context in an Activity, but wanting that a coroutine that write something to the DB is not cancelled at the end of the activity. Or maybe there's another alternative?
    e
    • 2
    • 4
  • p

    Pavel.AZ

    11/28/2018, 11:29 AM
    Hey, since Actor and Channels are ObsoleteCoroutinesApi, what should we use instead?
    r
    • 2
    • 1
  • b

    bloder

    11/28/2018, 12:19 PM
    Hi, what's the best way to run many tasks in parallel at the same time and wait its results with coroutines?
    • 1
    • 1
  • d

    Diefferson

    11/28/2018, 1:12 PM
    Hi, based on class Result I create class ResultAsync to encapsulate Coroutines results, what do you think about?
    u
    • 2
    • 4
  • b

    bdawg.io

    11/29/2018, 6:47 AM
    Is there a way to configure the maximum number of active concurrent coroutines in a CoroutineScope/Context?
    g
    • 2
    • 6
  • t

    Tolriq

    11/29/2018, 9:05 AM
    Is there a simple way to have a channel / workerpool that can only have 1 active coroutine? (Meaning that any message send while the coroutine is running would be dropped). From reading I understand that CONFLATED will have 1 in the queue + 1 running, and that RendezVous would suspend the send and not ignore it.
    g
    u
    • 3
    • 54
  • m

    mingkangpan

    11/29/2018, 11:08 AM
    I have a question: if I am launching a coroutines, and want to return and cancel it, if some if condition doesn't fullfil how do I do? like this?
    launch {
       val isYes = channel.receive
       if(!isYes) {
           coroutineContext.cancel()
           return@launch
       }
       
       //process further logic
    }
    d
    • 2
    • 2
  • g

    gotoOla

    11/29/2018, 1:30 PM
    Are there any known memory gotchas that were introduced with the 1.0 release and switch to structured concurrency (where launch and async are extensions on a coroutinescope?) The reason why I am asking is that we have had a service running for quite a long while with kotlin 1.2.61 and when we tried to bump it to kotlin 1.3 we are continously increasing in memory until we eventually crash
    o
    k
    g
    • 4
    • 8
  • m

    myanmarking

    11/29/2018, 7:14 PM
    i would assume in #1 the scope gets captured inside the foorLoop, which isnt the case
    f
    g
    • 3
    • 6
  • d

    dewildte

    11/30/2018, 5:06 AM
    Anybody working with kotlin's actors?
    ☝️ 1
    o
    • 2
    • 6
  • j

    Joey Heck

    11/30/2018, 8:03 PM
    val job = GlobalScope.launch {
        <How do I access the Job from here>
    }
    t
    • 2
    • 3
  • t

    Tolriq

    11/30/2018, 8:07 PM
    What is the proper way to implement suspendCancellableCoroutine but for coroutine / suspend code?
    suspend fun doLoad() = suspendCancellableCoroutine<Result> {
            val cancellationSignal = CancellationSignal()
            it.invokeOnCancellation { cancellationSignal.cancel() }
            val result = query.cancellationSignal(cancellationSignal).executeAsync()
            if (cancellationSignal.isCanceled) {
                it.resume(Result.Cancelled)
            } else {
                it.resume(Result.Success(result))
            }
        }
    In that example all works if executeAsync is blocking, but if executeAsync is a suspend function this no more works. Since cancellation rely on the cancellation signal how to merge the 2 worlds?
    d
    • 2
    • 4
  • v

    v79

    12/01/2018, 8:12 AM
    Suppose I have an arbitrary list of
    suspend
    functions p(), q(),..., and I want them to run in parallel/concurrently. Is this a valid approach?
    -.kt
    g
    u
    d
    • 4
    • 12
Powered by Linen
Title
v

v79

12/01/2018, 8:12 AM
Suppose I have an arbitrary list of
suspend
functions p(), q(),..., and I want them to run in parallel/concurrently. Is this a valid approach?
-.kt
g

gildor

12/01/2018, 11:24 AM
yes, you can use launch (if you don’t need result of invocation) This covered in official guide https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/composing-suspending-functions.md#concurrent-using-async
v

v79

12/01/2018, 12:44 PM
Thanks. This is all very new to me 🙂
u

uli

12/01/2018, 1:30 PM
Why do you need the outer launch?
v

v79

12/01/2018, 1:36 PM
Turns out I don't, it just appeared in the tutorial I was working from and I copied blindly 🙂. I've taken it out.
d

Dico

12/02/2018, 1:52 AM
I don't think the code you wrote works. The
launch
invocations are using dispatcher provided by
runBlocking
scope, which uses the
Which queues the coroutines on the same thread
Instead, you can consider using GlobalScope, or even better, declaring your function as an extension on CoroutineScope interface. You can also put it in a component that has its own CoroutineScope.
Or just pass a dispatcher as context to the top most launch
u

uli

12/02/2018, 4:16 AM
@Dico why do you think the code would not work on a single thread?
If all coroutines are surrended must of the time a single thread will do just fine.
d

Dico

12/02/2018, 7:41 AM
What I meant to say is that I think the code will run on a single thread (as I eloquently explained) while the poster explicitly wants to run tasks in parallel.
@uli
View count: 2