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

    Slackbot

    12/20/2018, 4:45 PM
    This message was deleted.
    d
    n
    • 3
    • 3
  • a

    Allan Wang

    12/21/2018, 12:17 AM
    If I have code that previously used the continuation style:
    doA {
      doB {
        doC()
      }
    }
    And I want to make them all in the same level, would it be done like the following?
    // Original
    fun doA(continuation: () -> Unit) {
      // some action
      continuation()
    }
    
    // New
    suspend fun doA() = suspendCoroutine<Unit> {
      // some action
      it.resume(Unit)
    }
    Then I do something like
    launch {
      doA()
      doB()
      doC()
    }
    Which should occur one after the other by default. My goal is just to remove the nested brackets. The reason I have continuation to begin with is that the actions I’m running deal with callbacks. Is there also a benefit to doing some potential safety checks before calling suspendCoroutine vs putting them all inside that wrapper? The delay function seems to do that.
    g
    d
    • 3
    • 10
  • a

    Allan Wang

    12/21/2018, 12:46 AM
    To those who replied to my previous post, does this look good?
    // Original
    private fun setWebCookie(cookie: String?, callback: (() -> Unit)?) {
        with(CookieManager.getInstance()) {
            removeAllCookies { _ ->
                if (cookie == null) {
                    callback?.invoke()
                    return@removeAllCookies
                }
                L.d { "Setting cookie" }
                val cookies = cookie.split(";").map { Pair(it, SingleSubject.create<Boolean>()) }
                cookies.forEach { (cookie, callback) -> setCookie(FB_URL_BASE, cookie) { callback.onSuccess(it) } }
                Observable.zip<Boolean, Unit>(cookies.map { (_, callback) -> callback.toObservable() }) {}
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe {
                            callback?.invoke()
                            L.d { "Cookies set" }
                            L._d { cookie }
                            flush()
                        }
            }
        }
    }
    
    // With suspension
    private suspend fun suspendSetWebCookie(cookie: String?) {
        cookie ?: return
        val manager = CookieManager.getInstance()
        manager.removeAllCookies()
        cookie.split(":").forEach {
            manager.setSingleWebCookie(it)
        }
    }
    
    private suspend fun CookieManager.removeAllCookies(): Boolean = suspendCoroutine { cont ->
        removeAllCookies {
            cont.resume(it)
        }
    }
    
    private suspend fun CookieManager.setSingleWebCookie(cookie: String): Boolean = suspendCoroutine { cont ->
        setCookie(FB_URL_BASE, cookie) {
            cont.resume(it)
        }
    }
    The use of RX initially was slight overkill, given there’s no thread switching or anything really asynchronous in my logic. I’m going to ignore the error handling for now.
    g
    • 2
    • 1
  • p

    pakoito

    12/21/2018, 1:11 AM
    the concept behind with the singleton, mutating, and parsing using string split would flag for me in code review
    a
    • 2
    • 1
  • p

    pakoito

    12/21/2018, 1:12 AM
    given there’s no thread switching or anything really asynchronous in my logic
    looks overkill here too unless you have something that does IO in removeAllCookies and setCookie
    g
    • 2
    • 4
  • k

    Kulwinder Singh

    12/21/2018, 9:22 AM
    Ho to make this call async
    videosList.forEachIndexed { index, video: BaseVideo ->
                val userData = getUserData(video)*//calling suspend function* 
                listWithData[index].userData = userData
            }
    g
    • 2
    • 29
  • o

    obobo

    12/21/2018, 1:43 PM
    Hello, I'm using resilience4j and I'm trying to figure out a pattern: I want to a function call in a circuit breaker, but this function suspends, so the compiler won't let me do it.
    decorateCheckedSupplier(circuitBreaker) {
      suspendingFunction() // compiler complains
    }
    How would I handle this? I've realized that I can wrap the
    suspendingFunction
    call in an
    async
    block, but then the circuitbreaker returns a
    Deferred
    and always succeeds, which is not what I want. What I want, I think, is to have be able to call a suspending function from an arbitrary lambda.
    s
    g
    m
    • 4
    • 7
  • m

    Marcelo Velloso

    12/21/2018, 2:40 PM
    I have a question on coroutines. I want to launch two coroutines asynchronously and wait on whichever completes first, is this possible? The context here is that two separate server calls can be made independently and if either returns an error I want to cancel the remaining coroutine and error out.
    s
    b
    • 3
    • 6
  • v

    Vsevolod Tolstopyatov [JB]

    12/21/2018, 4:11 PM
    📣 📣 📣
    kotlinx.coroutines
    version 1.1.0 is here! Changelog (compared to 1.1.0-alpha): * Kotlin updated to 1.3.11. * Resumes of
    CancellableContinuation
    in the final state now produce
    IllegalStateException
    . This change does not affect previous
    CancellableContinuation
    improvement, races between resume and cancellation do not lead to exceptional situation. *
    runBlocking
    is integrated with
    Dispatchers.Unconfined
    . Now nested
    runBlocking
    and unconfined calls do not hang, but share the same event loop.
    🎁 2
    :kotlin: 8
    😒uspend: 14
    ❤️ 3
    🎉 16
    :kotlin-flag: 4
    🎄 2
    🍾 2
    🚟 3
    p
    • 2
    • 3
  • i

    itnoles

    12/21/2018, 4:14 PM
    is it very weird that tag set to 1.1.1?
    v
    • 2
    • 1
  • j

    Jurriaan Mous

    12/21/2018, 9:31 PM
    "Kotlin/Native single-threaded workers support: coroutines can be safely used in multiple independent K/N workers." Are there examples of this?
    g
    • 2
    • 2
  • d

    dewildte

    12/22/2018, 7:18 PM
    @[removed] I would like to play with the Actor Models being made. How would I go about doing so? The
    typed-actors
    branch is 394 commits behind master. Should I make a fork?
    v
    • 2
    • 1
  • g

    gmariotti

    12/25/2018, 9:24 AM
    First of all, Merry Christmas everyone 😄 !! Quick question, did something change in Coroutines 1.1.0 in how exceptions are propagated? Because in the kotlin module for Vert.x, there’s a test like this
    @Test
      fun `test failure event method`(testContext: TestContext) {
        GlobalScope.launch(vertx.dispatcher()) {
          val async = testContext.async()
          val cause = RuntimeException()
          try {
            awaitEvent<Any> { throw cause }
            testContext.fail()
          } catch (e: Exception) {
            testContext.assertEquals(cause, e)
          }
          async.complete()
        }
      }
    with
    awaitEvent
    implemented in this way:
    suspend fun <T> awaitEvent(block: (h: Handler<T>) -> Unit): T {
      return suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
        try {
          block.invoke(Handler { t ->
            cont.resume(t)
          })
        } catch (e: Exception) {
          cont.resumeWithException(e)
        }
      }
    }
    and now this test pass only if I do
    testContext.assertEquals(cause, e.cause)
    l
    e
    p
    • 4
    • 13
  • g

    goldin

    12/25/2018, 9:43 PM
    Hi. I have some problem with
    Channel
    . Where is my error?
    -.kt
    g
    • 2
    • 6
  • b

    bdawg.io

    12/26/2018, 4:38 AM
    Does
    future
    cancel the parent
    Job
    if the block fails exceptionally? (same behavior as
    async
    )
    g
    • 2
    • 3
  • a

    Allan Wang

    12/26/2018, 4:57 AM
    I want to make a flyweight using coroutines, where requests pass in a key and take in a value. If the value has already been requested within some amount of time, I want to reuse it, and if multiple requests are made with the same key, I only want the value to be fetched once and used for all requests. (This is very similar to this:

    https://www.youtube.com/watch?v=a3agLJQ6vt8▾

    ). Anyone should also be able to invalidate a current value, so that it is fetched again by future requests. I wrote a mock up here, but I’m wondering a few things: • Is it okay to wrap all of the channels in a single
    select
    ? That is one of the differences here compared to the example in the video • Is the usage of
    launch
    within the main
    fetch
    method acceptable? It is there purely to send an event to a channel while allowing me to use the coroutine continuation • Is it acceptable that all the maps are global. In the example, they are all within the
    launch
    code. I’m not sure if this affect access from a different thread or not.
    Flyweight.kt
    d
    • 2
    • 1
  • k

    kenkyee

    12/26/2018, 12:31 PM
    I don't see any synchronization in that code. The coroutines could conceivably run on different threads unless you give it a single threaded scope AFAIK
    a
    • 2
    • 2
  • m

    marcoferrer

    12/26/2018, 4:10 PM
    I wanted to get some feedback in regards to requiring proper usage of parallel decomposition (wrapping service method in coroutineScope). Currently for my library its up to the consumers to follow best practices outlined in the structure concurrency blog post.
    l
    • 2
    • 8
  • l

    louiscad

    12/26/2018, 5:38 PM
    Hi, I'm trying to implement a
    race
    function that would take a list of
    Deferred
    , await for the single fastest (biased or not, doesn't matter), cancel all the "losers", and return the value of the winner. Did someone already solve this problem, or has a clue on how to make this? Thank you!
    g
    a
    +2
    • 5
    • 18
  • r

    Rohan Maity

    12/26/2018, 8:14 PM
    Are Coroutines JVM specific ?
    🇳🇴 8
    g
    • 2
    • 2
  • b

    breandan

    12/27/2018, 5:11 AM
    Is it possible to define delimited continuations? What is the closest analogy to Scala's `shift`/`reset` construction using Kotlin coroutines? https://www.scala-lang.org/old/node/2096
    e
    • 2
    • 2
  • a

    Allan Wang

    12/27/2018, 6:07 AM
    In this example, running the code will print ‘done’, ‘1 end’, then ‘2 end’, each in a different thread. However, the for loop never seems to run. If I change both
    launch
    to
    launch(<http://Dispatchers.IO|Dispatchers.IO>)
    , then the loops each print 3 times. What’s going on here? In production, would I be expected to specify a different context if I want the loops to produce results? Was adding the loops in separate launches not enough?
    -.kt
    b
    • 2
    • 11
  • d

    dave08

    12/27/2018, 1:04 PM
    If I have
    class Foo { suspend fun execute(): Bar }
    and I want to limit that
    execute
    should not run in parallel is the simplest way (without channels) to use
    newSingleThreadContext
    to create one thread context in the class and use it in
    withContext(executeContext)
    in
    execute
    ? Is there anything wrong with this, or a better way?
    d
    • 2
    • 12
  • r

    Romanow

    12/27/2018, 3:03 PM
    Hi! Does anyone know how to stop the threads started by the
    CoroutineScheduler
    ? I'm trying to use coroutines from a webapp, where kotlin is loaded by the webapp classloader, so I need to cleanup all resources that I allocated. For this I have my own
    ExecutorCoroutineDispatcher
    that is used trough the code based on a internal
    ScheduledThreadPoolExecutor
    . But this seems to still startup some default thread pools...
    s
    t
    • 3
    • 3
  • z

    zak.taccardi

    12/27/2018, 7:20 PM
    I want an
    actor
    that I can cancel and restart. Is that possible?
    l
    a
    u
    • 4
    • 14
  • s

    simon.vergauwen

    12/27/2018, 8:29 PM
    Hi all 👋 A bunch of our test broke after bumping coroutines from
    1.0.0
    to
    1.1.0
    , this seemed to be caused by coroutines changing the exception instance under the hood. However this only occurs test packages. Is this expected behavior?
    t
    • 2
    • 2
  • z

    zak.taccardi

    12/27/2018, 9:25 PM
    I have a pretty complex flow of some jobs I need to run. I need to ensure proper cancellation and cleanup. I’m almost there - but I have some weird logic involving the two child jobs that need to run in parallel
    val actor = scope.actor<StartNewJobCommand> {
        var fatherJob: Job? = null
        for (startNewJobCommand in channel) {
            // cancel old father AND both his children if they are still running
            fatherJob?.cancelAndJoin() // wait to start new job until old job is complete
            fatherJob = launch {
                val son1 = async {
                    // .. 
                    // completion of this Deferred should cancel fatherJob and son2's job
                }
                val son2 = async {
                    // ..
                    // completion of this Deferred should cancel fatherJob and son1's job 
                }
                // fatherJob should not complete until his two sons have finished their work
                // note - only one of the two children need to finish
                son1.await()
                son2.await()
            }
        }
    }
    d
    • 2
    • 12
  • g

    groostav

    12/27/2018, 11:30 PM
    Do we have any idea when the visibility of methods like
    onCompletionInternal
    et-al will either be made public or disappear? I presume there's some work involving
    JobSupport
    that needs to happen. I'm trying to write my own class that extends
    AbstractCoroutine
    , but I'm having a real difficult time.
    e
    • 2
    • 1
  • r

    Rohan Maity

    12/28/2018, 3:45 AM
    Couroutines lets you do the asynchronous work in Non Blocking thread way I used three launch{} with delay (200) in UI thread Only . So Can I say it's like Time division in UI thread . Like when first launch {} is delay(200) , then UI thread becomes Idle and second launch {} begins to execute then . Please correct me if wrong ?
    g
    • 2
    • 13
  • a

    asad.awadia

    12/28/2018, 5:40 PM
    @elizarov why did kotlin not go the go route with coroutines and having a scheduler deal with moving things off onto other threads? Was the aim to give more fine grained control to the developer?
    l
    e
    • 3
    • 2
Powered by Linen
Title
a

asad.awadia

12/28/2018, 5:40 PM
@elizarov why did kotlin not go the go route with coroutines and having a scheduler deal with moving things off onto other threads? Was the aim to give more fine grained control to the developer?
l

louiscad

12/30/2018, 5:52 PM
You're partly right regarding giving more fine grained control. Kotlin strives to be explicit. That's why you need to be specific about where a coroutine is launched, where you want to switch execution context (which is not just about dispatcher BTW), and that's why we have structured concurrency in kotlinx.coroutines.
👍 1
e

elizarov

01/06/2019, 9:51 PM
That. And we also needed to support single-threaded UI frameworks like Swing and Android.
👍 1
View count: 5