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

    uli

    04/19/2018, 8:49 PM
    @bj0 i care for the order. I want to abort with an exception, as soon as any of the jobs throws. If I'd do
    deferredExports.foreach { it.await() }
    and the first job takes the longest, I'd only get the exception of another job, after the first terminates.
    v
    • 2
    • 4
  • g

    groostav

    04/19/2018, 11:35 PM
    So I recently had a horrifying revelation and I'm wondering if we could get a Doug Lea-like person to either confirm my suspicions or tell me I'm crazy. I wanted a
    SequentialPoolExecutor
    , so I wrote one, and tested it. The idea is that every
    submit
    or
    execute
    call is sequential-ized such that no submitted job will run before another submitted job completes. This is not necessarily single threaded as one very simple optimization we can employ is to back this SequentialExecutor with a pool, where the first-available thread is selected to run the job. My goal for such a component would be to allow me to write code like this:
    class SomeStatefulComponent {
      private val data = MutableDataStructureThatIsntThreadSafe()
    
      suspend fun doMutation(args: Args): Double = run(SequentialExecutor) { 
        data += transform(args)
        return data.moreComputation()
      }
    }
    and not worry about using nasty
    @Volatile
    or
    Unsafe
    or
    AtomicReference
    or more generally CAS/locking strategies. Instead such an executor would elegantly serialize everything for me. But the problem, thinking back to concurrency in practice, is that which
    @Volatile
    was originally designed to solve: if some mutable state on
    data
    is put into a thread-local cache, then even squentially run jobds might get their correctness ruined by such a cache. Effectively this boils down to an apocalyptic assumption: is it really the case that fields not marked for explicit thread sharing cannot ever be shared between threads? Does somebody have a clever way to make this non-functional problem into a functional one via use of a fuzz-testing or other concurrency-testing strategy?
    v
    • 2
    • 2
  • m

    mp

    04/20/2018, 12:40 AM
    Unfortunately, especially on x86, hammering on stuff hoping for rare failures tends to only produce results that imply that x86 has a very strong memory model. 😉 If you can't convince yourself with sufficient perusal of JCIP that there's a happens-before chain, it's probably wrong.
    👍 1
    g
    • 2
    • 2
  • l

    louiscad

    04/20/2018, 7:00 AM
    Should I use
    Channel(capacity = UNLIMITED)
    +
    offer(...)
    or a rendez-vous
    Channel()
    +
    launch { send(...) }
    ?
    v
    • 2
    • 2
  • l

    louiscad

    04/20/2018, 3:59 PM
    The default dispatcher for runBlocking coroutine, in particular, is confined to the invoker thread
    Is this still true? Isn't
    runBlocking
    now using
    DefaultDispatcher
    , which is equal to
    CommonPool
    on JVM/Android? Quote from here, second paragraph, third sentence: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#unconfined-vs-confined-dispatcher
    🤔 1
    p
    • 2
    • 1
  • d

    Dexter

    04/20/2018, 6:33 PM
    I need to ramp up quickly on idiomatic Kotlin patterns using coroutines with both blocking and non-blocking I/O. Does anyone have any substantial experience in this area? In particular, I will like to know how suspend fuctions with blocking network I/O performs against non-suspend functions using NIO.
    c
    l
    g
    • 4
    • 5
  • u

    uli

    04/20/2018, 7:58 PM
    Coroutines make using nio simpler. For blocking io they provide little benefit as they will need one thread per io channel anyway
    d
    • 2
    • 8
  • j

    julioyg

    04/23/2018, 1:47 PM
    👋 I need a bit help, I'm trying go from an async complex op in rx to a simpler implementation using coroutines, so first step is to get my observable returning a value, to do so I'm using
    suspendCoroutine
    so:
    suspend fun myFunc = suspendCancellableCoroutine{continuation ->
      myObservable.subscribe(onsuccess={continuation.resume(it)}, onError={continuation.resume(error(it)})
       continuation.invokeOnCompletion(onCancelling = true) {disposable.dispose()}}
    Thing is that when I cancel the coroutine that calls the function, it doesn't dispose the observable, is there anyway to make the function to cancel immediately? as the doc says even if the coroutine is cancelled it doesn't mean that the code will be cancelled but instead we should check regularly inside that code whether is't cancelled or not, but, is there any alternative?
    v
    • 2
    • 2
  • j

    julioyg

    04/23/2018, 1:55 PM
    @gildor I've just come up with your lib and wonder, how you'd cancel a request when the coroutine get's cancelled? (sorry for the ping but the most similar scenario that comes to mi mind is that you launch a network call within a coroutine and cancel it, but it wouldn't cancel the request, would it?)
    g
    i
    • 3
    • 20
  • v

    voddan

    04/23/2018, 2:36 PM
    Urgent help needed! Is this adaptation of the coroutine tutorial correct, or did I miss something?
    import org.springframework.util.concurrent.ListenableFuture
    import org.springframework.util.concurrent.ListenableFutureCallback
    
    public suspend fun <T> ListenableFuture<T>.await(): T = suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
        val callback = ContinuationCallback(cont)
        this.addCallback(callback)
        cont.invokeOnCompletion {
            callback.cont = null // clear the reference to continuation from the future's callback
        }
    }
    
    private class ContinuationCallback<T>(@Volatile @JvmField var cont: CancellableContinuation<T>?) : ListenableFutureCallback<T> {
        @Suppress("UNCHECKED_CAST")
        override fun onSuccess(result: T?) { cont?.resume(result as T) }
        override fun onFailure(t: Throwable) { cont?.resumeWithException(t) }
    }
    v
    • 2
    • 2
  • p

    petersommerhoff

    04/24/2018, 7:58 AM
    For the sake of completeness, I should mention that cancellation is not only possible at suspension points, you can also check
    isActive
    yourself to stop execution -- all of Kotlin's suspending functions do that so they also enable cancellation
    d
    g
    • 3
    • 19
  • a

    AJ Alt

    04/24/2018, 5:20 PM
    Is there an equivalent to
    select
    that doesn't abort if one of the coroutines throws an exception?
    p
    • 2
    • 1
  • d

    dekans

    04/25/2018, 9:32 AM
    Is there a notion of priority with coroutines? I'd like to do some job in background but I'd like it to be executed ASAP, before other queued & less important jobs
    p
    e
    +2
    • 5
    • 31
  • i

    igorvd

    04/25/2018, 2:40 PM
    is there any way to achieve something similiar with the
    throttle
    operator using coroutines?
    v
    b
    • 3
    • 10
  • h

    hannesstruss

    04/25/2018, 8:11 PM
    I have a basic question about how
    isActive
    works:
    fun main(args: Array<String>) = runBlocking {
      val job = Job()
    
      val pool = newFixedThreadPoolContext(2, "Cool")
      repeat(2) {
        launch(pool, parent = job) {
          startLoop()
        }
      }
    
      delay(1000)
    
      println("Canceling")
      job.cancel()
    
      delay(1000)
    
      println("End")
    
      Unit
    }
    
    suspend fun startLoop() {
      while (isActive) {
        println("I'm active: ${isActive} in ${Thread.currentThread().name}, my job is cancelled: ${coroutineContext[Job]?.isCancelled}")
        Thread.sleep(500)
      }
    }
    calling
    job.cancel()
    will not terminate the loops. The complete output is:
    I'm active: true in Cool-1, my job is cancelled: false
    I'm active: true in Cool-2, my job is cancelled: false
    I'm active: true in Cool-1, my job is cancelled: false
    I'm active: true in Cool-2, my job is cancelled: false
    I'm active: true in Cool-2, my job is cancelled: false
    I'm active: true in Cool-1, my job is cancelled: false
    Canceling
    I'm active: true in Cool-1, my job is cancelled: true
    I'm active: true in Cool-2, my job is cancelled: true
    I'm active: true in Cool-1, my job is cancelled: true
    I'm active: true in Cool-2, my job is cancelled: true
    End
    In my real life situation, instead of
    Thread.sleep
    , the coroutine is waiting to read from a blocking queue (poll with timeout). If I use
    delay(500)
    instead of sleeping, the coroutines are cancelled properly. Does a Coroutine have to suspend in order for isActive to change?
    m
    p
    • 3
    • 20
  • a

    albertgao

    04/26/2018, 1:04 AM
    How to cancel a coroutine inside the coroutine? Something like in normal coding, I can do
    return
    , then the statement after this
    return
    will not be executed. But what about inside a coroutine? You can’t
    return
    in a coroutine. Seems the answer is
    coroutineContext().cancel()
    , But with
    Anko
    , it said
    coroutineContext of type CoroutineContext can't be invoked as a function
    g
    • 2
    • 13
  • b

    bj0

    04/26/2018, 1:39 AM
    you can throw a
    CancellationException
    a
    • 2
    • 1
  • m

    marstran

    04/26/2018, 10:36 AM
    I don't think that function can be tail call optimized even without the suspend modifier. The recursive call is within the let-block.
    u
    • 2
    • 4
  • d

    dknapp

    04/26/2018, 2:02 PM
    are there any plans to include coroutines in the stdlib or will they always require an additional library?
    v
    • 2
    • 3
  • g

    groostav

    04/26/2018, 11:33 PM
    even if we for-go the "use a channel not a blockable queue", which is rather abstract, you could use standard kotlin
    @ReplaceWith
    for something like
    launch {
      //replace 
      staticallyKnownAsBlockingQueueInstance.take()
      //with
      run(BLOCKABLE_THREAD_POOL) { staticallyKnownAsBlockingQueueInstance.take() }
    }
    inducing a compiler error at
    BLOCKABLE_THREAD_POOL
    ... unlness kotlinx.coroutines can be updated to include such a dispatcher embedded in itself.
    a
    • 2
    • 3
  • d

    Dmytro Danylyk

    04/27/2018, 1:21 PM
    https://twitter.com/dmytrodanylyk/status/989856782808825856
    😋 4
    r
    l
    • 3
    • 3
  • d

    Dmytro Danylyk

    04/27/2018, 1:22 PM
    Let me know if there is better way ⤴️
    v
    d
    • 3
    • 11
  • d

    dekans

    04/29/2018, 12:07 PM
    Can we set thread priority when using or initializing a dispatcher? Or maybe Coroutines system is designed to handle this? I see (on Android) that all threads from
    CommonPool
    or custom from
    newSingleThreadContext
    inherit the normail priority level. Which makes them equal to the main thread. Is there another mechanism to make the UI thread not affected? I'd like to make sure to prioritize it.
    g
    v
    • 3
    • 5
  • j

    jw

    04/30/2018, 2:18 PM
    you should use
    runBlocking
    👍🏼 1
    d
    • 2
    • 4
  • d

    dave08

    05/01/2018, 4:43 AM
    fun ReceiveChannel. toDeferred() = async { single() }
    , @spierce7 maybe, but probably not such good practice in coroutines to do such a thing though...
    s
    • 2
    • 43
  • m

    Marharyta Nedzelska

    05/03/2018, 7:41 AM
    Is there any way to convert guava ListenableFuture into Kotlin Deferred? I see that there is an extension method await on ListenableFuture in kotlin-coroutines-guava but it is not what I need
    d
    v
    e
    • 4
    • 4
  • l

    louiscad

    05/04/2018, 2:00 PM
    Hi, can't the
    cancel()
    methods in
    Channel
    and
    Job
    be optimized to not allocate a new
    CancellationException
    when the channel is already closed or the job is already cancelled or completed?
    v
    • 2
    • 7
  • v

    voddan

    05/08/2018, 3:52 PM
    Hi! If I have a
    newSingleThreadedCoroutrineContext
    , and a bunch of coroutine launched with it, a) will the coroutines execute in the order of their creation? b) will the execution prefer the first coroutine more than the last after some suspends and resumes?
    v
    • 2
    • 1
  • a

    adeln

    05/09/2018, 10:26 AM
    like: I create a channel, and once it's closed I need to invoke some callback to clean up
    l
    • 2
    • 2
  • w

    withoutclass

    05/09/2018, 3:26 PM
    wasn't sure I missed something in the library before I try to roll my own
    v
    • 2
    • 2
Powered by Linen
Title
w

withoutclass

05/09/2018, 3:26 PM
wasn't sure I missed something in the library before I try to roll my own
v

Vsevolod Tolstopyatov [JB]

05/10/2018, 1:14 PM
There isn’t any built-in mechanism in the library.
DelayChannel
(https://github.com/Kotlin/kotlinx.coroutines/issues/327) will be added in the next release, which will simplify things for you. You can find examples of usage in related pull request
w

withoutclass

05/10/2018, 8:16 PM
Wow thank you!
View count: 8