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

    Paul Woitaschek

    02/23/2017, 11:49 AM
    Why dont you execute immediately when on the ui thread already?
    g
    • 2
    • 2
  • p

    Paul Woitaschek

    02/23/2017, 11:58 AM
    @robin
    r
    • 2
    • 2
  • p

    Paul Woitaschek

    02/23/2017, 12:58 PM
    @elizarov I was thinking about the rx-java coroutine .await. I think it might make sense to create a wrapping class that encapsulates the error / sucess.
    e
    g
    • 3
    • 9
  • g

    gildor

    02/23/2017, 1:10 PM
    might make sense to create a wrapping class that encapsulates the error / sucess
    @Paul Woitaschek I use this approach for my coroutine wrapper for Retrofit: https://github.com/gildor/kotlin-coroutines-retrofit#awaitresult
    .await
    returns sealed class Result
    p
    • 2
    • 2
  • p

    Paul Woitaschek

    02/24/2017, 10:34 AM
    @elizarov why don't you include completable?
    e
    • 2
    • 4
  • n

    nimtiazm

    02/25/2017, 10:04 AM
    i fired up htop and noticed that when i execute the java program all CPUs’ hit 100% consumption while in kotlin programs they hit 91% or 95% and in between
    e
    • 2
    • 1
  • p

    Paul Woitaschek

    02/26/2017, 12:12 PM
    But that whole start / stop / interrupt / post on UIThread logic is messy
    e
    • 2
    • 20
  • p

    Paul Woitaschek

    02/28/2017, 10:28 AM
    But I have multiple modules, maybe its related to that?
    e
    • 2
    • 5
  • f

    frankdavid

    02/28/2017, 12:52 PM
    Could someone quickly summarise it or point me to a doc where it is summarised, how kotlin coroutines are different from Quasar? They both seem to offer almost the same capabilities.
    e
    • 2
    • 3
  • k

    kirillrakhman

    03/01/2017, 2:56 PM
    referenced in https://github.com/Kotlin/kotlinx.coroutines
    e
    • 2
    • 5
  • g

    gildor

    03/01/2017, 3:46 PM
    @elizarov Will
    kotlinx-coroutines
    be published to jcenter? I’m updating library but still cannot use kotlinx-coroutines without
    maven { url "<https://dl.bintray.com/kotlin/kotlin-eap-1.1>" }
    e
    • 2
    • 2
  • k

    kevinherron

    03/01/2017, 9:11 PM
    @elizarov is the Async suffix the convention you’ve landed on?
    e
    • 2
    • 2
  • g

    groostav

    03/02/2017, 12:22 AM
    and i dont understand
    RestrictsSuspension
    😞
    e
    • 2
    • 1
  • r

    robin

    03/02/2017, 8:54 AM
    @cypher121 I think that would actually not be a good idea. I think I would stumble a lot over trying to find a function I know is there, but not being able to find it, because I forgot to make the current function a suspend fun.
    c
    • 2
    • 1
  • e

    elizarov

    03/02/2017, 1:46 PM
    @kingsley Yes. It is inverted, though. Jobs can have multiple children and when a job completes, all its children are cancelled. So, instead of creating a composite subscription you just launch all the relevant coroutines as children of your job. In some respect every Job is a potential composite (can have an arbitrary number of children). You can read more and find an example in "Children of a coroutine" section of the guide: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md
    👍 1
    k
    • 2
    • 1
  • e

    elizarov

    03/03/2017, 4:43 PM
    Here is a hint. You can read "Go concurrency patterns". Most of them directly translate to Kotlin coroutines.
    i
    • 2
    • 1
  • r

    rakshakhegde

    03/04/2017, 4:43 AM
    Is there a good document that explains how coroutines in Kotlin work? It's fascinating how it's suspending without threads 😯
    v
    g
    • 3
    • 5
  • k

    kingsley

    03/04/2017, 7:35 AM
    I have a setup like this one:
    // File A: Some repository
    fun fetchFooAsync = async(CommonPool) { ... }
    
    // File B: Android activity
    private val job = Job()
    
    fun loadFooIntoUI() {
      launch(Android + job) {
        fetchFooAsync().await()
        ...
      }
    }
    When the activity in B is getting destroyed, I can easily call
    job.cancel()
    , and the coroutine in
    loadFooIntoUI
    is canceled correctly. However, the
    fetchFooAsync
    call still continues indefinitely. Is there a way to neatly cancel everything altogether without having to explicitly pass
    job
    to
    fechFooAsync
    ?
    👍 1
    d
    • 2
    • 2
  • k

    kingsley

    03/04/2017, 8:03 AM
    The only other way I could do this is to add an
    invokeOnCompletion
    to the returned Job for
    launch
    , but that takes away the fun since I have to repeat it everywhere
    e
    • 2
    • 5
  • v

    v0ldem0rt

    03/04/2017, 8:21 AM
    I don't have to write boiler plate 😄 wow
    e
    • 2
    • 5
  • e

    elizarov

    03/04/2017, 3:18 PM
    The key advantage of coroutines is that they let you avoid callback hell. For example, you can replace deeply nested flatmaps with a simple and easy-to-understand imperative-style "do this, do that" code. If you don't have any of that and all your Rx code is just "take this IO result, switch to UI thread, display it" or "take this button click, then do some IO", then you will not find much difference between Rx and coroutines.
    a
    • 2
    • 2
  • o

    oshai

    03/04/2017, 5:34 PM
    Is there any coroutine implementation for mysql/jdbc?
    e
    • 2
    • 5
  • j

    jw

    03/04/2017, 7:18 PM
    The most interesting part of Android is that it's main thread is just a special case of a general system. I would expect a first-party offering to be able to use any Handler, not just one wrapped around the main Looper.
    👍 3
    g
    • 2
    • 1
  • e

    elizarov

    03/04/2017, 8:50 PM
    Making it a class that can accept any Handler is easy. I'll do it. Naming the instance for the main thread is hard. I'll run a poll on Monday.
    g
    • 2
    • 4
  • c

    cedric

    03/05/2017, 4:05 AM
    @elizarov Did you mean "Confine coroutine execution on a non main thread"? Coroutines are typically network or file stuff, they should be kept out of the the EDT
    e
    • 2
    • 2
  • e

    elizarov

    03/05/2017, 7:09 AM
    It is Ok, but under high load (lots of CPUs, lots of ops)
    ConcurrentHashMap
    is better.
    👍 1
    v
    • 2
    • 8
  • e

    elizarov

    03/05/2017, 12:18 PM
    And last thing. It is better not to use
    Async
    in the name of suspending function. This naming is better to be reserved for functions that start asynchronous operation and return immediately, usually with some kind of future/deferred result. The async part the name serves as a reminder to the invoker of this function that they should not ignore the result, but must await for it or compose it into a larger computation in some way. There is no such risk with suspending functions, and the async in their name is superfluous.
    ➕ 1
    👍 1
    v
    • 2
    • 1
  • d

    deviant

    03/05/2017, 4:14 PM
    fetchData is something like firebaseReference.addValueEventListener(listener) in my real code. it is totally safe to call from UI thread. it registers callback that can be triggered many times. Also it is necessary to unregister callback when activity is destroyed or when we dont need updates anymore. so i need some mechanism to catch cancel event inside this method
    fun dataChannel(context: CoroutineContext) = produce<Any>(context) {
            val listener = object : Listener {
                override fun onSuccess(value: Any) {
                    offer(value)    // emit to channel
                }
    
                override fun onError(throwable: Throwable) {
                    close(throwable)    // close channel
                    //throw throwable
                }
            }
            addListener(listener)
            
            fetchData() // invoke callback's onResult here
            
            // need to register removeListener() somewhere
        }
    k
    e
    • 3
    • 9
  • v

    v0ldem0rt

    03/06/2017, 5:40 AM
    Guys I just wrote an article on Kotlin coroutines https://medium.com/@zohaibhassan/in-pursuit-of-better-jvm-futures-kotlin-coroutines-281a79211b09#.npk9flsxm let me know if I messed up somewhere 😛
    👍 6
    v
    a
    • 3
    • 4
  • a

    adambl4

    03/06/2017, 12:00 PM
    @elizarov have you considered a different name for
    suspend fun Completable.await()
    since rx.Completable has a member function with the same name?
    e
    b
    • 3
    • 9
Powered by Linen
Title
a

adambl4

03/06/2017, 12:00 PM
@elizarov have you considered a different name for
suspend fun Completable.await()
since rx.Completable has a member function with the same name?
e

elizarov

03/06/2017, 12:05 PM
adambl4: Yes. Did not found anything good. Meanwhile, I’ve just removed
Completable.await
from Rx 1.x module. It is not a problem with Rx 2.x. It does not have this name conflict (there is no
Completable.await
there)
b

bamdmux

03/06/2017, 12:19 PM
In Rx2 theyre called blockingAwait() which describes better the behaviour
Maybe .suspendAwait() for the ones on kotlinx coroutines?
e

elizarov

03/06/2017, 12:22 PM
await
seems to be a more natural name and you already get a visual cue in IDE that this is a suspending invocation going on.
I like the naming in Rx2 and, since Rx1 is reaching EOL this year, hopefully it is not going to be a long-term issue.
I wish all the blocking methods would have been as clearly marked as in Rx 2 in all the different APIs and libs we have.
b

bamdmux

03/06/2017, 12:33 PM
@elizarov I meant only for the rx1 as a temporary solution. Agree that await is the preferred choice
And yes, a lot of libraries could follow the example of Rx 2
e

elizarov

03/06/2017, 12:45 PM
It is just really a few lines of code. You can copy it from the Rx 2.x lib if you really need it (take it from
develop
branch, though, — there is a bug in master version of Rx2 Completable.await)
View count: 4