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

    mayojava

    10/03/2018, 7:00 AM
    from my understanding the first
    async
    should get cancelled after the exception since they are in the same scope.
    k
    • 2
    • 2
  • f

    Felix

    10/03/2018, 5:01 PM
    Consider the following scenario: - High-latency HTTP requests, done using the Apache Async Client - Coroutine that "launches" multiple requests using
    async
    , obtaining
    Deferred
    objects - Coroutine then cancels one of those
    Deferred
    objects. 1) How can such a
    cancel
    trigger a cancellation on the pending HTTP request? The Apache Async Client has a way to cancel requests, however since there isn't any thread actively monitoring the
    isActive
    , I need to "link" the
    Deferred
    cancel with the pending request cancel. For instance, in .NET the
    CancellationToken
    as a
    Register
    method to register an action to be performed. 2) Also, if the coroutine decides to ignore the cancellation (e.g. it is to late to cancel the HTTP request), how can we observe that on the
    Deferred
    ? What I'm observing is that the
    await
    will throw the
    JobCancellationException
    even if the
    cancel
    is ignored.
    e
    • 2
    • 5
  • n

    nimtiazm

    10/04/2018, 5:13 AM
    I created a jvm project and used coroutines version 0.30.1-eap13 with kotlin 1.3.0-rc-146. When I spin up my main method a basic coroutine, i get the following exception: Exception in thread “main” java.lang.NoClassDefFoundError: android/os/Looper at kotlinx.coroutines.android.HandlerDispatcherKt.<clinit>(HandlerDispatcher.kt:60)
    h
    e
    d
    • 4
    • 17
  • n

    nimtiazm

    10/04/2018, 5:15 AM
    why exactly is it looking for android class?
    e
    • 2
    • 1
  • e

    elizarov

    10/04/2018, 11:20 AM
    We have two versions.
    0.30.1
    for the people still on experimental (Kotlin 1.2) coroutines, and
    0.30.1-eap13
    for people who are playing with RC of Kotlin 1.3 where coroutines are no longer experimental
    • 1
    • 1
  • p

    Paul Woitaschek

    10/04/2018, 2:28 PM
    Can we get a hotfix for kotlinx.coroutines requiring 1.3.0?
    👍🏼 2
    :yes: 1
    v
    d
    u
    • 4
    • 10
  • u

    uhe

    10/04/2018, 2:54 PM
    The question really comes down to what you mean by "running in parallel"... do you consider suspended coroutines to be "running"? Or do you only count active coroutines currently executing on thread as "running"?
    👍🏼 1
    e
    • 2
    • 1
  • d

    dave08

    10/04/2018, 2:55 PM
    Maybe that's what you're looking for?
    e
    u
    • 3
    • 3
  • m

    muralimohan962

    10/05/2018, 4:47 AM
    Hi! I am a newbie to coroutines. Are there any recommendations as to when to use coroutines and threads?
    e
    t
    +2
    • 5
    • 7
  • a

    Albert

    10/05/2018, 8:14 AM
    If I wanted to start some block as a long running process with multiple `async`/`launch`, should I use
    withContext
    ?
    withContext(GlobalScope.coroutineContext) {
      async {
      }
      launch {
      }
    }
    e
    l
    • 3
    • 7
  • k

    Konstantin Petrukhnov

    10/05/2018, 11:51 AM
    Is there example of other example? E.g. when coroutines help, and that not involve running same task with different data (sequentially/async)?
    e
    l
    • 3
    • 2
  • k

    kirillrakhman

    10/05/2018, 11:52 AM
    Would it make sense to have an inspection that warns when you have a suspending function that's an extension on CoroutineScope?
    e
    • 2
    • 1
  • a

    Albert

    10/05/2018, 12:09 PM
    I don't understand why
    currentScope
    is deprecated. For example:
    suspend fun httpGetAsync(): Deferred<String> = currentScope {
        async {
            // ... Do HTTP GET
        }
    }
    
    suspend fun main() {
      coroutineScope {
        val request1 = httpGetAsync()
        val request2 = httpGetAsync()
        
        println("${request1.await()} - ${request2.await()")
      }
    }
    If
    httpGetAsync
    was using
    coroutineScope
    , it means that
    request2
    will be filled when
    request1
    is completely done.
    j
    s
    • 3
    • 5
  • v

    voddan

    10/05/2018, 3:31 PM
    I mean, anything is better than a 5-word name that we have now. How about Delegates.fixedPool?
    e
    j
    d
    • 4
    • 8
  • n

    nwh

    10/07/2018, 12:38 AM
    Are there any really good readings on using channels and actors? Explaining basics, examples, use cases, etc
    e
    • 2
    • 1
  • h

    Hadi Tok

    10/07/2018, 2:04 PM
    I want to execute the coroutines in the for loop in parallel and when all complete I want
    print(5)
    to run. how should I go for doing this? the current code I sent runs the coroutines in loop parallel but
    print(5)
    does not wait for completion of the others.
    -.kt
    d
    d
    +2
    • 5
    • 16
  • r

    redrield

    10/07/2018, 4:44 PM
    if I have a Sequence from buildSequence, is there a way to collect all the elements it's already yielded and not care about anything else
    d
    a
    d
    • 4
    • 7
  • e

    elizarov

    10/07/2018, 6:36 PM
    Conceptually yes, but the second code is hot, too. Coroutine still runs. For an example of a cold stream try
    sequence { }
    . It is truly cold. But it is synchronous. We don’t have async cold streams yet.
    v
    k
    • 3
    • 4
  • n

    nwh

    10/07/2018, 6:43 PM
    How can I support cancellation within a
    suspend
    function? If I don't use
    launch/async
    etc to launch anything
    e
    • 2
    • 6
  • t

    TwoClocks

    10/07/2018, 6:59 PM
    I don't quite understand the contexts. For example, if I remove the runBlocking{} from the following code, it runs fine w/ the "done blocking" running in some random worker thread. But w/ the runBlocking{}, and that block never exits. I'm trying to run all the coroutines the main thread. code :
    fun main(args : Array<String>) {
        var taskHandle:Continuation<Unit>?=null
    
        runBlocking { // If I run in this context, this block never exits.
    
            launch {
                while(true) {
                    println("about to block")
                    val retVal = suspendCoroutine<Unit> {
                        taskHandle = it;
                    }
                    println("done blocking.. on thread : ${Thread.currentThread().name}")
                }
            }
            println("done launching")
        }
    
        println("all coroutines blocked, do work...")
    
        repeat( 10, {
            Thread.sleep(ThreadLocalRandom.current().nextInt(2000) + 500L)
            taskHandle!!.resume(Unit)
        })
    }
    d
    k
    • 3
    • 8
  • s

    sarel

    10/08/2018, 2:51 AM
    I see the coroutines-nio package has been removed recently. Any reason for this - is there an alternative?
    g
    • 2
    • 2
  • r

    Rohit Surwase

    10/08/2018, 5:29 AM
    Hi, I am new to kotlin and just started using Coroutines. I have few doubts. 1. If Coroutines is a language feature then why do we need to add dependencies? 2. How can I try latest 1.3 RC version in Android Studio? I tried following (and of course at its right place)
    // Downloaded 1.3. early preview plugin of Kotlin for Android Studio
    
    ext.kotlin_version = '1.3.0-rc-46'
    // ext.kotlin_version = '1.3.0-rc-57'
    maven { url '<https://dl.bintray.com/kotlin/kotlin-eap>' }
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    
    implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-core:0.30.1") {
            exclude group: "org.jetbrains.kotlinx", module: "atomicfu-common"
        }
        implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.30.1'
    Above setup giving me error
    No route to host (connect failed)
    3. What is working for me is just
    ext.kotlin_version = '1.2.71'
    
    implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-core:0.30.1") {
            exclude group: "org.jetbrains.kotlinx", module: "atomicfu-common"
        }
        implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.30.1'
    Please guide me in the right direction. Thanks.
    d
    l
    b
    • 4
    • 5
  • k

    kenkyee

    10/08/2018, 5:44 AM
    For (1) coroutines need core support for primitives. Same thing is done in the .Net JVM. The library is the API on top.
    r
    • 2
    • 1
  • v

    Vsevolod Tolstopyatov [JB]

    10/08/2018, 4:14 PM
    📣 📣 📣
    kotlinx.coroutines
    version
    0.30.2
    . Release contains fixes for issues with
    Dispatchers.Main
    and various improvements. Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/0.30.2
    👏 3
    🎉 9
    :kotlin-flag: 3
    👍 2
    j
    g
    • 3
    • 6
  • g

    gildor

    10/09/2018, 5:20 AM
    we do not need to create our own threads in Android for any reason?
    @Rohit Surwase I don’t see any common reason even without coroutines create own threads on Android if you not a library author (usually you use ThreadPoolExecutor or some high level primitives) All those cases (1-3) are covered easily by coroutines and provide much better API without drawbacks. Especially if 1 and 2 have async api
    r
    g
    • 3
    • 8
  • g

    gildor

    10/09/2018, 5:21 AM
    But as standalone coroutines are deprecated what other alternatives do we have apart from GlobalScope
    What do you mean? GlobalScope is direct successor of old standalone coroutine builders and provides the same lifecycle. But usually you don’t need it, use CoroutineScope everywhere where it’s possible to do
    has examples about
    runBlocking{ }
    and
    GlobalScope.launch( )
    only
    It’s just for simplicity of examples, docs has actually a lot of different examples, not only runBlocking or GlobalScope
    r
    • 2
    • 11
  • m

    marcinmoskala

    10/09/2018, 3:07 PM
    https://youtrack.jetbrains.net/issue/KT-27474
    • 1
    • 1
  • j

    jw

    10/09/2018, 3:11 PM
    shouldn't you file that on the kotlinx library? doesn't seem related to the language or stdlib
    🆗 1
    m
    • 2
    • 1
  • p

    poohbar

    10/09/2018, 6:46 PM
    hi, i want just a simple
    parallelStream
    equivalent in kotlin.. does this make sense?
    runBlocking {
       myItems.map {
        GlobalScope.launch {
           // do something
        }
       }.forEach { it.join() }
    }
    
    // now do something with all items
    e
    n
    +2
    • 5
    • 10
  • n

    nwh

    10/09/2018, 8:58 PM
    Is passing the
    ctx
    to the
    launch
    method redundant in this scenario?
    val ctx = newSingleThreadContext("sample")
    val scope = CoroutineScope(ctx)
    scope.launch(ctx) { }
    l
    v
    • 3
    • 3
Powered by Linen
Title
n

nwh

10/09/2018, 8:58 PM
Is passing the
ctx
to the
launch
method redundant in this scenario?
val ctx = newSingleThreadContext("sample")
val scope = CoroutineScope(ctx)
scope.launch(ctx) { }
l

louiscad

10/09/2018, 10:02 PM
Yes it is. It will no-op because it's the same
v

voddan

10/10/2018, 8:35 AM
Why does
launch
accepts an optional context then? Can't the API be minimized to always use the scopes?
l

louiscad

10/10/2018, 8:44 AM
The additional and optional
CoroutineContext
is folded with the context from the scope. That gives you structured concurrency, but you can still launch in another dispatcher, or add something to the scope's context.
View count: 11