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

    bitkid

    04/05/2018, 11:30 AM
    hey guys. i have a question (which might be rather stupid). why does this test does not throw a TimeoutCancelationException?
    l
    1 reply · 2 participants
  • b

    bitkid

    04/05/2018, 11:33 AM
    doesnt work .. suspension function can be only called within coroutine body
    c
    1 reply · 2 participants
  • b

    bitkid

    04/05/2018, 11:57 AM
    would be nice to have some mockito addons for coroutine testing 🙂
    g
    1 reply · 2 participants
  • s

    streetsofboston

    04/05/2018, 1:30 PM
    @bitkid You may like this one as well for testing code that uses coroutines: https://github.com/Kotlin/kotlinx.coroutines/pull/297
    👍 1
    💪 2
    c
    b
    2 replies · 3 participants
  • j

    Joey Heck

    04/05/2018, 6:42 PM
    Last night our meetup topic was Coroutines and I wanted to implement them in a json parse, but it's not as fast as I expected
    val gson = GsonBuilder().create()
    val jsonArray: JSONArray = responseJsonObject.getJSONArray("Value")
    
    val parsedItemArray = List<Deferred<Item>>(jsonArray.length()) {
        async { gson.fromJson(jsonArray.get(it).toString(), Item::class.java) }
    }
    
    runBlocking {
        parsedItemArray .forEach { defered ->
            val item = defered.await()
        }
    }
    So I'm parsing an array of json objects in a JSON array using gson into a list of Deferreds. I call the parsing in an async, then I wait until they are all done. I call a timestamp before and after it's done the same code without coroutines runs faster
    val gson = GsonBuilder().create()
    val jsonArray: JSONArray = responseJsonObject.getJSONArray("Value")
    
    val parsedItemArray = List<Item>(jsonArray.length()) {
        gson.fromJson(jsonArray.get(it).toString(), Item::class.java)
    }
    I was using a parallel class (found on stack overflow) previously with much better results
    object Parallel {
    
        private val iCPU = Runtime.getRuntime().availableProcessors()
    
        interface LoopBody<T> {
            fun run(i: T)
        }
    
        fun For(start: Int, stop: Int, loopBody: LoopBody<Int>) {
            val executor = Executors.newFixedThreadPool(iCPU)
            val futures = LinkedList<Future<*>>()
    
            for (i in start until stop) {
                val future = executor.submit { loopBody.run(i) }
                futures.add(future)
            }
    
            for (f in futures) {
                try {
                    f.get()
                } catch (e: InterruptedException) {
                } catch (e: ExecutionException) {
                }
    
            }
    
            executor.shutdown()
        }
    }
    I call it with this
    val gson = GsonBuilder().create()
    val jsonArray: JSONArray = responseJsonObject.getJSONArray("Value")
    
    val parsedItemArray = arrayOfNulls<Item>(jsonArray.length())
    
    Parallel.For(0, jsonArray.length(), object : Parallel.LoopBody<Int> {
    	override fun run(i: Int) {
    		parsedItemArray[i] = gson.fromJson(jsonArray.get(i).toString(), Item::class.java)
    	}
    })
    g
    3 replies · 2 participants
  • j

    Joey Heck

    04/05/2018, 6:47 PM
    With my above code, Serialized parsing takes 3 seconds, Parallel takes 1.5, Coroutine takes 3-4 seconds
    e
    1 reply · 2 participants
  • j

    jw

    04/06/2018, 2:24 AM
    exception handling
    a
    4 replies · 2 participants
  • a

    altavir

    04/06/2018, 11:26 AM
    I've got a list of objects that have Deferred properties which produce some kind of reult, afteer result is produced, the Deferred is replaced by another (Completable)Deferred. Now I want to create a listener which will perform some action when any future is completed. I am trying to do so using
    select
    clause this way:
    val job = launch {
                while (true) {
                    select<Unit> {
                        stateHolder.forEach { state ->
                            state.future.onAwait {
                                    // do something
                            }
                        }
                    }
                }
            }
    But it does not seem to enter the select clause even once. What am I doing wrong?
    g
    5 replies · 2 participants
  • k

    Kulwinder Singh

    04/06/2018, 1:17 PM
    so my updated function is good i think
    g
    t
    7 replies · 3 participants
  • v

    venkat

    04/07/2018, 10:50 PM
    Crossposting: https://github.com/Kotlin/kotlinx.coroutines/issues/312
    g
    3 replies · 2 participants
  • d

    Dmytro Danylyk

    04/09/2018, 10:25 AM
    @elizarov can we make
    CoroutineContext#DEBUG
    field public and mutable? In android we usually rely on generated
    BuildConfig.DEBUG
    field.
    e
    v
    +1
    17 replies · 4 participants
  • p

    pakoito

    04/10/2018, 10:25 AM
    if you tell me which API is necessary to wrap, I could take a look for the next version
    g
    k
    15 replies · 3 participants
  • j

    jw

    04/10/2018, 4:20 PM
    https://youtrack.jetbrains.com/issue/KT-22228
    s
    g
    3 replies · 3 participants
  • j

    jkbbwr

    04/11/2018, 11:45 AM
    Is there a more spread out way of writing complex actors?
    e
    5 replies · 2 participants
  • t

    tapchicoma

    04/12/2018, 6:44 AM
    Hi, can anyone point me to any coroutine koans repo?
    t
    6 replies · 2 participants
  • b

    Bjarne Gelotte

    04/13/2018, 9:04 AM
    Hey! I'm learning about coroutines and have a pretty simple question (I think). I want to do two tasks concurrently:
    val first:  Deferred<Unit> = async { firstTask() }
    val second: Deferred<Unit> = async { secondTask() }
    
    first.await().let { doFirstStuff() }
    second.await().let { doSecondStuff() }
    In this example, will the
    doFirstStuff()
    always be called before
    doSecondStuff()
    ? Or can
    doSecondStuff
    trigger as soon as
    second
    is evaluated (this is what I want to achieve)?
    u
    3 replies · 2 participants
  • g

    gildor

    04/13/2018, 9:18 AM
    Why not just rewrite it like:
    val first:  Deferred<Unit> = async { 
       firstTask().let { doFirstStuff() }
    }
    val second: Deferred<Unit> = async {    
        secondTask().let { doSecondStuff() }
    }
    first.await()
    second.await()
    b
    13 replies · 2 participants
  • g

    gildor

    04/13/2018, 9:48 AM
    Suspend constructor? %)
    l
    g
    3 replies · 3 participants
  • d

    Daniel Tam

    04/13/2018, 12:37 PM
    Anyone know if there is a Promise.all() equivalent for
    Deferred<T>
    ?
    l
    v
    9 replies · 3 participants
  • u

    uli

    04/16/2018, 5:08 PM
    just out of curiosity, can you switch the order of the tests
    a
    7 replies · 2 participants
  • a

    Andrew Gazelka

    04/16/2018, 5:16 PM
    let's say I have 10_000 test cases which map to a float
    result
    . I want to quickly find a test case, where
    result < c
    , where
    c
    is a constant. Is there any way I can cleanly structure my code to achieve this?
    b
    8 replies · 2 participants
  • a

    Andrew Gazelka

    04/16/2018, 9:02 PM
    I am trying to use coroutines with connections. However,
    Jsoup
    connections uses blocking (
    Thread.sleep()
    I think)... this effectively makes each coroutine the same as a thread. Is there anyway to turn these API `sleep()`s into `delay()`s?
    g
    1 reply · 2 participants
  • a

    Andrew Gazelka

    04/16/2018, 9:14 PM
    nvm I got it—Java NIO
    p
    v
    5 replies · 3 participants
  • d

    Daniel Tam

    04/17/2018, 12:57 PM
    also a different question: I'm a little bit confused about what coroutine constructs have to be explicitly cancelled to free memory and what will be garbage collected automatically. Stuff like channels and jobs (outside a running coroutine) I assume will just get garbage collected without needing to call
    close
    or
    cancel
    on them?
    g
    4 replies · 2 participants
  • r

    Robert Menke

    04/17/2018, 1:39 PM
    Sorry if this has been asked a million times, but is there a coroutines equivalent to javascript’s
    Promise.all
    in the standard library? Something kind of along the lines of this… but better 😛
    fun <T>all(list : List<suspend () -> T>) : Deferred<List<T>> {
        return async {
            list.map { async { it() } }
                .map { it.await() }
        }
    }
    d
    s
    5 replies · 3 participants
  • w

    withoutclass

    04/17/2018, 5:54 PM
    I've been having some difficulty with debugging my coroutine code. When I set breakpoints within a coroutine, I am unable to see local variable using evaluate. I'm assuming I just don't get something in regards debugging coroutines.
    p
    1 reply · 2 participants
  • l

    louiscad

    04/18/2018, 6:54 AM
    Is this a good idea?
    mutex.withLock(owner = coroutineContext) {
       // Some suspend calls
    }
    v
    4 replies · 2 participants
  • d

    Dario Pellegrini

    04/18/2018, 8:05 AM
    @louiscad thank you, but I was searching a method to do that if exists without changing my network layer.
    l
    g
    +1
    7 replies · 4 participants
  • p

    petersommerhoff

    04/19/2018, 9:14 AM
    How can I pass a compiler flag like -Dkotlinx.coroutines.debug when running an app in Android Studio?
    c
    p
    +1
    20 replies · 4 participants
  • u

    uli

    04/19/2018, 7:39 PM
    Here is my code: (updated)
    while (deferredExports.any { !it.isCompleted && !it.isCompletedExceptionally }) {
                    select<Unit> {
                        deferredExports.forEach {
                            if (!it.isCompleted && !it.isCompletedExceptionally) {
                                it.onAwait {
                                }
                            }
                        }
                    }
                }
    v
    2 replies · 2 participants
Powered by Linen
Title
u

uli

04/19/2018, 7:39 PM
Here is my code: (updated)
while (deferredExports.any { !it.isCompleted && !it.isCompletedExceptionally }) {
                select<Unit> {
                    deferredExports.forEach {
                        if (!it.isCompleted && !it.isCompletedExceptionally) {
                            it.onAwait {
                            }
                        }
                    }
                }
            }
v

Vsevolod Tolstopyatov [JB]

04/20/2018, 8:02 AM
!it.isCompleted && !it.isCompletedExceptionally
is not necessary here in any sense:
await
performs same check and in this code it’s not atomic, so it’s possible to
await
deferred in
Completed
state after checking for
!isCompleted
. Check doesn’t improve neither readability nor performance
u

uli

04/20/2018, 8:14 AM
I know it's broken. But the idea was to not await any deferreds that have already been awaited. I'll check the solution from issue 171 you mentioned below
View count: 3