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

    pniederw

    01/20/2017, 11:32 PM
    yeah, spock (and gradle) used to be my life until two years ago. unfortunately, silicon valley doesn’t want their engineers to work on OSS, even in their spare time. 😞 Hope to get my OSS life back eventually.
    d
    o
    • 3
    • 6
  • e

    elizarov

    01/27/2017, 12:12 PM
    kotlinx-coroutines-rx
    does not support cancellation yet.
    b
    • 2
    • 1
  • h

    hackerham

    01/27/2017, 12:12 PM
    ok, then there's one small problem. CriticalStuff() cant return value that i use for fallback. I have to use external var
    e
    • 2
    • 7
  • o

    orangy

    01/28/2017, 1:07 PM
    @Deactivated User I’m a little bit concerned about naming. First, it looks confusingly similar to #ktor. Second, two-letter abbreviations of submodules doesn’t help me understand which module is doing what.
    d
    h
    • 3
    • 4
  • h

    hackerham

    01/28/2017, 2:02 PM
    next time, name it Korra
    d
    • 2
    • 1
  • d

    Deactivated User

    01/29/2017, 2:29 PM
    Well, in my last job we migrated our whole flash codebase to haxe initially, then to kotlin 🙂
    h
    • 2
    • 2
  • d

    dmitry.petrov

    01/31/2017, 9:37 AM
    In general, that's an arbitrary FSM, which can be pretty much incomprehensible for IDEA's decompiler
    k
    • 2
    • 3
  • p

    Paul Woitaschek

    01/31/2017, 10:04 AM
    I don't get the rxjava coroutines. Isn't the rxjava specifically designed for thread switching and combining data flows? What benefit do coroutines give?
    e
    a
    • 3
    • 15
  • o

    orangy

    01/31/2017, 8:04 PM
    Yep, scripting games would be nice fit for coroutines, e.g. quest scenario, non-path movements of monsters/NPC, etc. But in non-scriptable engines (like libgdx) it’s even more useful. E.g. consider a platform moving left and right. You will normally have to encode state machine by hand. With coroutines you can do it in a simple loop (pseudocode):
    class Platform(left: Float, right: Float, vertical : Float, speed : Float) : Actor() {
    …
    fun suspend behaviour() {
        while (true) {
          for (x in left..right step speed) {
              moveTo(x, vertical) // frame-synced suspend function
          }
          for (x in right downTo left step speed) {
              moveTo(x, vertical)
          }
       }
    }
    👍 4
    :kotlin: 1
    o
    • 2
    • 1
  • r

    rrader

    02/02/2017, 2:48 PM
    Is it possible somehow with Kotlin coroutines to do a behaviour like: a request(r1) comes to server, this request is handled in a thread from thread pool, server does some work in that thread, after this server make a request to remote server, at this moment this thread should be returned to thread pool to handle another request(r2), after remote server returned a response, request(r1) should continue work from moment when was made a remote request
    e
    • 2
    • 4
  • e

    elizarov

    02/07/2017, 7:42 AM
    kotlinx.coroutines
    version
    0.7-beta
    is published. It includes production-quality mostly lock-free implementation of Go-style channels that enable coroutines to safely share streams of arbitrary elements or messages without actually sharing any mutable state (e.g. share data by communicating). More details here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#channels
    👍 11
    d
    k
    • 3
    • 8
  • g

    groostav

    02/07/2017, 6:56 PM
    @elizarov nice work on the channels stuff. but its unusable:
    send
    and
    recieve
    are too conventional, its time we got some scala up in this and named them
    !
    and
    <-
    , or something similar. /sarcasm
    e
    • 2
    • 1
  • e

    elizarov

    02/08/2017, 7:51 PM
    The only significant difference I am aware of (beyond naming things), is that
    async
    in C#/JS/Dart uses implicit context (in C# that depends on the thread you are calling from, and in JS/Dart that's the event loop context), while in Kotlin we decided to make the context explicit.
    r
    • 2
    • 1
  • p

    pniederw

    02/09/2017, 3:44 AM
    @elizarov If you go forward with renaming
    defer
    to
    async
    , will you also rename
    future
    back to
    async
    ?
    e
    • 2
    • 19
  • v

    voddan

    02/09/2017, 4:54 AM
    If we combine it with renaming
    Deferred
    to
    Asynced
    , we can avoid the mismatch in names
    r
    e
    r
    • 4
    • 3
  • v

    voddan

    02/09/2017, 6:50 AM
    Also, @elizarov, what about the general naming for coroutine builders? AFAIR, the initial idea was to create an API which would feel somewhat like language constructs. That would imply using short one-syllabic names for coroutine builders and scoping functions, but now we have monsters like
    runBlocking {}
    , etc. Can't we rename that into
    blocking {}
    ?
    e
    • 2
    • 10
  • c

    cedric

    02/09/2017, 7:02 AM
    Call it
    blockBlock
    , a verb and a noun. Problem solved.
    :trollface: 4
    v
    k
    +2
    • 5
    • 15
  • a

    antonkeks

    02/09/2017, 8:29 PM
    CoroutineImpl seem to have been moved to another package between beta-18 and beta-38
    i
    • 2
    • 1
  • g

    gildor

    02/09/2017, 11:23 PM
    @elizarov ohh, I forgot to add link to the project repo, I should sleep more 😅 https://github.com/gildor/kotlin-coroutines-android
    e
    k
    • 3
    • 7
  • r

    rrader

    02/10/2017, 8:58 AM
    Maybe
    async
    should return
    Coroutine
    class
    e
    h
    • 3
    • 12
  • j

    julienviet

    02/10/2017, 3:45 PM
    @elizarov where will this be added ?
    e
    • 2
    • 2
  • e

    elizarov

    02/13/2017, 8:31 PM
    https://youtrack.jetbrains.com/issue/KT-15555
    👍 1
    r
    • 2
    • 2
  • g

    gaetan

    02/18/2017, 12:39 AM
    I wrote a first post on coroutines. If anybody wants to review it, you are welcome: https://medium.com/@gz_k/scale-out-pi-computation-with-kotlin-coroutines-4ee3ad294674 😉
    👍 7
    v
    j
    • 3
    • 3
  • p

    Paul Woitaschek

    02/20/2017, 8:31 PM
    How can I compose more sophisticated compsition like rxjavas switchMap?
    e
    • 2
    • 1
  • e

    elizarov

    02/20/2017, 9:41 PM
    You should not.
    suspendCoroutine
    is too low level. It takes large amount of code just to reliably pass a signal from one coroutine to the other. It is like writing your own blocking queue using volatile variables, atomics and LockSupport.
  • p

    Paul Woitaschek

    02/21/2017, 12:38 PM
    I don't argue against, I try to understand
    e
    • 2
    • 1
  • p

    Paul Woitaschek

    02/21/2017, 10:29 PM
    Would this be the right way to transition from rxjava to coroutine?
    e
    • 2
    • 2
  • m

    mkobit

    02/22/2017, 12:56 AM
    before i dive too deep into it, are there any thoughts for
    kotlinx-coroutines-jdk8
    library to support helpers for
    Channel
    that adapt it to a
    Stream
    ?
    e
    • 2
    • 2
  • v

    voddan

    02/22/2017, 4:38 PM
    One thing: could you please add a performance comparison of different techniques for reference? Statements like
    This is the fastest solution for this particular problem
    are not very reassuring
    e
    c
    • 3
    • 7
  • u

    uli

    02/23/2017, 9:09 AM
    Hi All, i've been doing some timings, based on variations of the "Shared mutable state and concurrency" examples form the coroutine guide and saw surprising results. First, here is my code:
    val massive = 1_000_000
    private suspend fun aMassiveRun(context: CoroutineContext = CommonPool, action: suspend () -> Unit) {
        val jobs = List(massive) {
            launch(context) {
                action()
            }
        }
        jobs.forEach { it.join() }
    }
    
    private object ThreadConfinement1: Callable<Int> {
        val counterContext = newSingleThreadContext("CounterContext")
    
        override fun call(): Int {
            var counter = 0
            runBlocking<Unit> {
                aMassiveRun(counterContext) {
                    counter++
                }
            }
            return counter
        }
    }
    
    private object ThreadConfinement2: Callable<Int> {
        val counterContext = newSingleThreadContext("CounterContext")
    
        override fun call(): Int {
            var counter = 0
            runBlocking<Unit> {
                aMassiveRun {
                    run(counterContext) {
                        counter++
                    }
                }
            }
            return counter
        }
    }
    I time both callables 5 times to warm up hotspot and only take the last measurement. Both tests run all incrementation on a single thread but ThreadConfinement2 does the scheduling of the actual work in form the CommonPool. The timings measured are 3.5s for ThreadConfinement2 while ThreadConfinement1 takes 5.8s on my machine. Can anyone explain, why ThreadConfinement2 is faster? This came as a big surprise to me. Edit: Further measurements did not support these numbers. I now get more expected timings of 2.6s for ThreadConfinement1 and 4.3s for ThreadConfinement2. I guess my machine was just doing funny things in the background. Timing things correctly is never easy in a multitasking environment.
    e
    • 2
    • 2
Powered by Linen
Title
u

uli

02/23/2017, 9:09 AM
Hi All, i've been doing some timings, based on variations of the "Shared mutable state and concurrency" examples form the coroutine guide and saw surprising results. First, here is my code:
val massive = 1_000_000
private suspend fun aMassiveRun(context: CoroutineContext = CommonPool, action: suspend () -> Unit) {
    val jobs = List(massive) {
        launch(context) {
            action()
        }
    }
    jobs.forEach { it.join() }
}

private object ThreadConfinement1: Callable<Int> {
    val counterContext = newSingleThreadContext("CounterContext")

    override fun call(): Int {
        var counter = 0
        runBlocking<Unit> {
            aMassiveRun(counterContext) {
                counter++
            }
        }
        return counter
    }
}

private object ThreadConfinement2: Callable<Int> {
    val counterContext = newSingleThreadContext("CounterContext")

    override fun call(): Int {
        var counter = 0
        runBlocking<Unit> {
            aMassiveRun {
                run(counterContext) {
                    counter++
                }
            }
        }
        return counter
    }
}
I time both callables 5 times to warm up hotspot and only take the last measurement. Both tests run all incrementation on a single thread but ThreadConfinement2 does the scheduling of the actual work in form the CommonPool. The timings measured are 3.5s for ThreadConfinement2 while ThreadConfinement1 takes 5.8s on my machine. Can anyone explain, why ThreadConfinement2 is faster? This came as a big surprise to me. Edit: Further measurements did not support these numbers. I now get more expected timings of 2.6s for ThreadConfinement1 and 4.3s for ThreadConfinement2. I guess my machine was just doing funny things in the background. Timing things correctly is never easy in a multitasking environment.
e

elizarov

02/23/2017, 9:47 AM
That makes sense and is straightforward to explain. I'll add the other approach to the thread confinement to the next revision of guide, too, as well as measurement results and the reasons behind them. I'll setup JMH b enchmarks around them to measure it all properly.
u

uli

02/23/2017, 12:50 PM
Cool. Thanks!
View count: 2