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

    Paul Woitaschek

    02/28/2018, 12:52 PM
    @elizarov What do you think about my suggestion to install an rx exception handler to all
    rxXYZ
    methods?
    e
    • 2
    • 12
  • l

    louiscad

    02/28/2018, 1:36 PM
    Hi, is there a way to have a
    ReceiveChannel
    / actor that cancels the work done for a value if a new one is received? My goal is to perform a computation for the latest received value and drop any in progress work.
    j
    • 2
    • 3
  • v

    voddan

    02/28/2018, 3:29 PM
    I wish it were
    launch(CommonPool.copy(parent = job)) {}
    Starting to think that the
    +
    was too cryptic to begin with
    j
    d
    e
    • 4
    • 14
  • w

    withoutclass

    02/28/2018, 3:54 PM
    Is there a recommended amount of time to use with
    delay
    if I want to make sure my routine is cooperative, but I don't need to actually delay anything? Is 1ms too little time? Curious if there is some best practice around that yet
    j
    • 2
    • 5
  • j

    jkbbwr

    03/01/2018, 1:21 PM
    Why can't local functions be suspendable
    e
    • 2
    • 3
  • t

    trathschlag

    03/01/2018, 2:52 PM
    Assumed I have an infinite source of tasks, for example some
    ReceiveChannel
    which lazily produces work and I want to schedule these on
    CommonPool
    . I can't just take every task from the source, because there are infinite. What's a good way to assure that for example always 1000 tasks are currently in my thread pool?
    e
    • 2
    • 3
  • d

    dave08

    03/02/2018, 10:31 AM
    Is there some practical use for the new
    suspend
    function in stdlib in 1.2.30? The release notes have an example that's not too clear to me what the point is...?
    suspend {     val result = deferredResult.await()     renderResult() }.startCoroutine(completion)
    g
    • 2
    • 7
  • l

    louiscad

    03/03/2018, 10:12 AM
    I'm starting to write a Medium article that aims to guide Android developers to use kotlinx.coroutines. I'll cover the basics to use coroutines correctly in Android apps. That includes how to use
    launch
    ,
    withContext
    ,
    async
    , the
    suspend
    modifier, which CoroutineContext to pick, what a
    Job
    is, how to wrap a callback with
    suspendCoroutine
    , how to handle errors, how to handle lifecycles of Android components. I'll also talk about some good libraries made on coroutines. Namely, @gildor and @jw ones for Retrofit. I'll also talk about channels and how it can be used for actors and to wrap true callback hells. Since this is my first public article, I'm unsure about the results, but I'm determined. I can share the draft to anyone willing to give feedback or willing to help in any other way. The current title of the draft article is kotlinx.coroutines intro for Android Devs. Please tell me if you dislike it or if you think you have a better one.
    👍 8
    d
    a
    • 3
    • 6
  • k

    kasper.kondzielski

    03/03/2018, 12:26 PM
    I already observed that when the second response arrived the
    isActive
    predicate returns
    false
    but I don't know how to prevent it
    d
    • 2
    • 3
  • d

    deviant

    03/04/2018, 11:57 AM
    Roman, are there any plans to publish
    kotlinx-coroutines-core-js
    on npm?
    e
    s
    • 3
    • 11
  • a

    acando86

    03/04/2018, 7:43 PM
    Not necessarily kotlin related, hope to not be OT, but i was wondering whether someone has good book/readings recommendation to learn more about concurrency models like CSP, actors etc in depth? i've started reading tony hoare's CSP book , but i was looking more for a comprehensive survey of different models.. i've some code examples in mind, but i still lack a solid understanding of the foundations of the subject.. any suggestion?
    l
    • 2
    • 3
  • v

    voddan

    03/05/2018, 12:41 PM
    If I create an interface with a method which potentially could be suspendible in some of the implementations in the future, do I get any penalty from marking this method
    suspend
    just in case?
    e
    • 2
    • 1
  • d

    deviant

    03/05/2018, 7:44 PM
    looks like
    kotlinx-coroutines-core-js
    doesn't work with
    create-react-kotlin-app
    ? i'm doing
    npm i kotlinx-coroutines-core --save
    and still can't use launch/async etc. or should i import these functions with @JsModule?
    e
    • 2
    • 4
  • p

    Paul Woitaschek

    03/06/2018, 4:20 PM
    What is the best way to get a future into the coroutine world?
    j
    • 2
    • 11
  • d

    dave08

    03/06/2018, 4:51 PM
    But in Android
    FutureTask
    can receive a callback when it's finished, so you wouldn't have to block an extra thread to wait for the result... and it implements Future from api level 1...
    j
    • 2
    • 14
  • j

    jw

    03/06/2018, 4:54 PM
    coroutines are just callbacks!
    n
    • 2
    • 1
  • j

    jw

    03/06/2018, 4:56 PM
    Roman and
    kotlinc
    suffer in it on our behalf
    😖 1
    😆 9
    o
    k
    • 3
    • 2
  • p

    pakoito

    03/06/2018, 8:25 PM
    java.lang.IllegalStateException: Already resumed
    So, `CoroutineContext`s are not reusable
    m
    e
    • 3
    • 16
  • e

    elizarov

    03/07/2018, 1:14 PM
    channel.consumeEach { …. }
    . The rest of the code will execute only when the channel is closed
    j
    • 2
    • 5
  • d

    deviant

    03/07/2018, 2:30 PM
    @elizarov
    public fun <E, R> ReceiveChannel<E>.flatMap(context: CoroutineContext = Unconfined, transform: suspend (E) -> ReceiveChannel<R>): ReceiveChannel<R>
    is there any chance we will see overloaded flatmap in the lib with such param signature
    transform: (E) -> Iterable<R>
    ?
    j
    e
    i
    • 4
    • 8
  • d

    dai

    03/08/2018, 9:58 AM
    I may have missed it but is there anyway to fire and forget an async call within a suspend function?
    j
    b
    • 3
    • 11
  • l

    louiscad

    03/09/2018, 8:22 AM
    Hi, just had an idea: What about showing an icon in the gutter or a "bar" on the left in the IDE to show where a higher order suspend function starts (e.g.
    launch
    and any other function whose lambda is a
    suspend
    one)? This could be a play sign with the curve, similar to the arrow with the curve we have for suspension points. This would help knowing where suspend calls are allowed in current code, helping to see potentially unneeded coroutines launches
    o
    e
    d
    • 4
    • 6
  • p

    Paul Woitaschek

    03/09/2018, 9:40 AM
    I'm looking for some kind of permanent continuation. I have a function that at some point has to wait on a callback. So I could use suspendCoroutine and store the continuations in a queue. The callback could then then pop the queue items and call resume on each. However it would be more elegant to have some kind of lock object so suspending functions could lock on it and then all resume when the lock object gets unlocked. Is there something built in for that?
    e
    d
    • 3
    • 6
  • i

    ivanmorgillo

    03/09/2018, 10:55 AM
    I'm looking for some examples about migrating a Rx based code base to a more coroutines based. any blog post about wrapping `Single`s and `Observable`s that you would suggest?
    👍 1
    d
    • 2
    • 1
  • p

    pakoito

    03/09/2018, 11:04 AM
    @elizarov did you write any adapter between CoroutineContext and Rx Schedulers? Is there even any correlation?
    j
    e
    g
    • 4
    • 10
  • s

    stepango

    03/11/2018, 11:20 AM
    @Jonathan that wasn't the question i asked, callback is there for a reason
    j
    • 2
    • 1
  • s

    stepango

    03/11/2018, 3:47 PM
    @gildor sure
    fun main(args: Array<String>) {
        launch(EmptyCoroutineContext) {
            withContext(EmptyCoroutineContext) {
                CompletableFuture.runAsync {
                    print("Hello")
                }.await()
            }
        }
    }
    
    suspend fun <T> CompletableFuture<T>.await() = suspendCoroutine<T> { cont ->
        cont.resume(join())
    }
    Hello
    would never be printed in this case
    g
    • 2
    • 1
  • b

    bj0

    03/11/2018, 3:53 PM
    why are you even bothering to use
    launch
    and
    withContext
    ?
    s
    • 2
    • 3
  • s

    stepango

    03/11/2018, 3:56 PM
    @Jonathan example with single thread context you proposed
    fun main(args: Array<String>) {
        val context = newSingleThreadContext("test")
        launch(context) {
            withContext(context) {
                CompletableFuture.runAsync {
                    print("Hello")
                }.await()
            }
        }
    }
    
    suspend fun <T> CompletableFuture<T>.await() = suspendCoroutine<T> { cont ->
        cont.resume(join())
    }
    Not working😮
    j
    i
    • 3
    • 15
  • o

    oshai

    03/12/2018, 9:58 AM
    We are using actor, similar to that example: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#actors I would like to "wake" the actor every couple of seconds to do work (ie handle messages it is holding as its state) is there an example for this? what is the best approach?
    j
    • 2
    • 2
Powered by Linen
Title
o

oshai

03/12/2018, 9:58 AM
We are using actor, similar to that example: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#actors I would like to "wake" the actor every couple of seconds to do work (ie handle messages it is holding as its state) is there an example for this? what is the best approach?
j

Jonathan

03/12/2018, 10:06 AM
Actor always wake up as soon as possible after receiving an element.
// take care of thread safety of the queue
val messages: Queue 

// Create an actor design to receive "wake-up" message (Unit can be used as an element type)
// Conflated buffer is usefull to not buffer "wake-up" messages if the process is longuer than the time between two wake-ups
val actor = actor<Unit>(capacity = Channel.CONFLATED) {
    consumeEach {
        // process pending messages
    }
}

init {
    launch {
        while(isActive) {
		
			// wait 2 seconds
            delay(2, TimeUnit.SECONDS)
			
            // awake the actor
            actor.send(Unit)
        }
    }
}
o

oshai

03/12/2018, 11:17 AM
thanks
View count: 7