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

    pardom

    03/19/2019, 5:49 PM
    `launch`: fire and forget `async`: wait for something
    b
    6 replies · 2 participants
  • q

    quver

    03/19/2019, 8:34 PM
    Hello guys, could you please tell me why exactly in examples
    Job
    was added to the
    coroutineContext
    override val coroutineContext: CoroutineContext
            get() = Dispatchers.Main + job
    ?
    s
    g
    42 replies · 3 participants
  • g

    groostav

    03/19/2019, 9:38 PM
    hey here's a basic question: is
    Channel
    a monad?
    s
    a
    7 replies · 3 participants
  • j

    JoakimForslund

    03/20/2019, 10:30 AM
    Any chance of ever seeing coroutines in androidNative? It would be greatly appreciated to be able to use both iOS and androidNative directly instead of having to use JNI communication
    g
    e
    10 replies · 3 participants
  • a

    arnaud.giuliani

    03/20/2019, 3:08 PM
    Hello all, I have a question about
    structured concurrency
    . If I understand, the thing is to ensure that we reuse a proper
    CoroutineScope
    instead of launching coroutines in the `Global`f scope. Then here is my question. I have 2 components:
    A
    &
    B
    . My component
    A
    initiate a coroutine scope and I can run functions against that. How do I share/propagate it to my component
    B
    on which I want to call functions.
    class A {
    	val coroutineContext: CoroutineContext ...
    }
    
    class B {
    	fun myFunction(){
    		// run with A.coroutineContext?
    	}
    }
    Do we have to pass the
    coroutineContext
    as an argument to any call of
    B
    ?
    b
    g
    +4
    301 replies · 7 participants
  • k

    kevinherron

    03/20/2019, 6:37 PM
    anyone else still having issues with breakpoints in
    suspend
    functions / coroutines not working?
    i
    g
    +1
    7 replies · 4 participants
  • m

    Marc Knaup

    03/21/2019, 4:17 AM
    Am I correct that
    .produce
    immediately starts its
    block
    even if there is no subscriber for the
    ReceiveChannel
    yet? If so, how can I avoid that?
    o
    2 replies · 2 participants
  • g

    ghedeon

    03/21/2019, 7:56 AM
    How to wrap
    Deffered
    into another
    Deferred
    with a custom exception? There is no coroutine context in that place, so I can't use
    .await()
    1 reply · 1 participant
  • j

    joelpedraza

    03/21/2019, 2:09 PM
    fun <A, B> Deferred<Pair<A, B>>.split(): Pair<Deferred<A>, Deferred<B>>
    Is this possible?
    g
    s
    +1
    23 replies · 4 participants
  • m

    Marc Knaup

    03/21/2019, 3:35 PM
    Are `ReceiveChannel`s closed automatically somehow if you for-loop over them even if you
    break
    at some point?
    s
    r
    15 replies · 3 participants
  • l

    louiscad

    03/21/2019, 5:25 PM
    I find myself needing something like this for use in
    while (true)
    loops because
    while (isActive)
    continues execution and doesn't throw:
    @UseExperimental(InternalCoroutinesApi::class)
    fun CoroutineContext.checkIsActiveOrCancelNow() {
        val job = get(Job)
        if (job != null && !job.isActive) throw job.getCancellationException()
    }
    This is quite useful in loops where I implement retrying. The alternative to that
    coroutineContext.checkIsActiveOrCancelNow()
    call is to use
    if (isActive.not()) yield()
    , but I find that it doesn't communicate the intent well. Do you think this should be integrated into kotlinx.coroutines? I'm personally inclined to open an issue there, but I want to know if I'm not alone first.
    :yes: 1
    v
    3 replies · 2 participants
  • s

    spierce7

    03/22/2019, 1:44 AM
    Is there a way for a child coroutine to access it's parent coroutine context?
    l
    1 reply · 2 participants
  • a

    asad.awadia

    03/22/2019, 2:25 AM
    What is the difference between actor model and fan out from the guide? https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/channels.md#fan-out
    o
    r
    6 replies · 3 participants
  • c

    curioustechizen

    03/22/2019, 12:45 PM
    We're converting a callback-style API into a coroutine using
    suspendCancellableCoroutine
    . We're looking for ways to signal progress in addition to completion and error. Currently, we pass a channel as a parameter to the suspending function through which we signal progress (this is conceptually similar to having a callback for progress). Are there other options? Like using the continuation object to signal progress?
    s
    d
    6 replies · 3 participants
  • i

    Icaro Temponi

    03/22/2019, 4:37 PM
    Is is possible to change the parallelism of the Default dispatcher (if yes, how?) or I'll need to create a dispatcher from a pool with $parallelism number of threads?
    g
    g
    32 replies · 3 participants
  • a

    asad.awadia

    03/22/2019, 11:28 PM
    Dunno if the question makes sense
    d
    2 replies · 2 participants
  • a

    asad.awadia

    03/23/2019, 5:18 AM
    if you have something like javalin a simple http server
    import io.javalin.Javalin
    
    fun main(args: Array<String>) {
        val app = Javalin.create().start(7000)
        app.get("/") { ctx -> ctx.result("Hello World") }
    }
    is it possible somehow to add coroutine support to this i.e. each request gets launched in its own coroutine and allows me to have controllers which are composed of suspending functions - maybe allow me to return a response on the context object from a launched coroutine?
    o
    o
    7 replies · 3 participants
  • r

    ribesg

    03/25/2019, 10:14 AM
    How would I implement a sequence doing HTTP request using the Ktor client? I get an error about restricted suspending functions when using
    sequence { }
    g
    f
    +1
    36 replies · 4 participants
  • s

    Satyam Agarwal

    03/26/2019, 7:43 AM
    Hi, I am a newbie in coroutines, And I am trying to use
    ScheduledExecutorService
    with coroutines, and I am not getting anywhere. I have a scheduled task that does not return anything. So I somehow want to use
    launch
    with the
    ScheduledExecutorService
    . Can anyone please help
    o
    4 replies · 2 participants
  • p

    Paul Woitaschek

    03/26/2019, 8:36 AM
    I.e. that a coroutine launched in onStart will get cancelled in onStop, onCreateView -> onDestroyView, onCreate -> onDestroy; etc?
    r
    s
    +2
    35 replies · 5 participants
  • t

    tjohnn

    03/26/2019, 11:00 AM
    I am quite new to coroutines and I don't seem to understand some basic examples:
    fun main() = runBlocking {
    //sampleStart
        launch {
            repeat(1000) { i ->
                println("I'm sleeping $i ...")
                delay(500L)
            }
        }
        delay(1300L) // just quit after delay
    //sampleEnd    
    }
    Prints 3 lines and exits because it uses a daemon thread
    I'm sleeping 0 ...
    I'm sleeping 1 ...
    I'm sleeping 2 ...
    But main waits for
    coroutineScope
    to finish execution
    fun main() = runBlocking { // this: CoroutineScope
        launch { 
            delay(200L)
            println("Task from runBlocking")
        }
    
        coroutineScope { // Creates a new coroutine scope
            launch {
                delay(900L) 
                println("Task from nested launch")
            }
    
            delay(100L)
            println("Task from coroutine scope") // This line will be printed before nested launch
        }
    
        println("Coroutine scope is over") // This line is not printed until nested launch completes
    }
    And prints this
    Task from coroutine scope
    Task from runBlocking
    Task from nested launch
    Coroutine scope is over
    Is there a magic done by
    coroutineScope
    that makes it block the main from finishing? Any help is appreciated.
    m
    r
    17 replies · 3 participants
  • w

    winchester044

    03/26/2019, 4:32 PM
    Hello folks, we have recently started experimenting with CoroutineWorker APIs from WorkManager. Is there any way to customize the underlying scope and exceptionHandler in for these workers(given the job object is internal in the class and we can only override the dispatcher)?
    l
    1 reply · 2 participants
  • v

    Vsevolod Tolstopyatov [JB]

    03/26/2019, 5:57 PM
    📣 📣 📣
    kotlinx.coroutines
    1.2.0-alpha is here! This is an alpha version of the major release with a lot of improvements in debuggability, diagnostics and performance. Changelog: * Debug agent now merges real stacktraces with coroutine stacktraces, its API is cleaned up and debug agent is on its road to stabilization *
    CoroutineTimeout
    test rule for JUnit4 to simplify testing and debugging with coroutines * Futures are now integrated with structured concurrency *
    Dispatchers.Unconfined
    ,
    MainCoroutineDispatcher.immediate
    ,
    MainScope
    and
    CoroutineScope.cancel
    are promoted to stable API *
    CompletableJob
    is introduced,
    Job()
    and
    SupervisorJob()
    are now completable *
    ensurePresent
    and
    isPresent
    extensions for
    ThreadLocal
    *
    ensureActive
    extensions for
    CoroutineContext
    ,
    CoroutineScope
    and
    Job
    * Operator
    invoke
    on
    CoroutineDispatcher
    ...and a lot more, full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.2.0-alpha
    🎉 17
    😒uspend: 8
    d
    p
    +2
    6 replies · 5 participants
  • a

    andrea.santurbano

    03/27/2019, 8:19 AM
    Hi everyone I'm working with Kafka via Kotlin and we want to transform its
    Future
    implementation (https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/clients/producer/internals/FutureRecordMetadata.java) as
    Deferred
    . Could this be a solution?
    fun <T> Future<T>.asDeferred(): Deferred<T> {
        return GlobalScope.async(<http://Dispatchers.IO|Dispatchers.IO>) {
            get()
        }
    }
    @rocketraman suggested to follow also this solution: https://stackoverflow.com/questions/50793362/how-to-use-suspendcoroutine-to-turn-java-7-future-into-kotlin-suspending-functio#answer-52901712 Which of these two is the most correct?
    h
    r
    3 replies · 3 participants
  • m

    mohsenoid

    03/27/2019, 9:47 AM
    Hi there, We are migrating some parts of our over-used RxJava codes to Coroutines, but we cannot decide which one is the best practice as a new learners! old code is something like this:
    interface CallLogDataStore {
        fun getCallLogs(): Single<Array<CallLogEntity>>
    }
    
    class CallLogDataStoreImpl @Inject internal constructor(
        private val contentResolver: ContentResolver
    ) : CallLogDataStore {
    
        override fun getCallLogs(): Single<Array<CallLogEntity>> = Single.fromCallable(::queryAllCallLogs)
    we can change it to
    Deferred
    from the source:
    interface CallLogDataStore {
        suspend fun getCallLogsAsync(): Deferred<Array<CallLogEntity>>
    }
    
    class CallLogDataStoreImpl @Inject internal constructor(
        private val contentResolver: ContentResolver
    ) : CallLogDataStore {
    
        override suspend fun getCallLogsAsync(): Deferred<Array<CallLogEntity>> =
            suspendCoroutine { queryAllCallLogs() }
    or just keep it simple and let the use-case decide to execute it using Coroutines or not,
    interface CallLogDataStore {
        fun getCallLogs(): Array<CallLogEntity>
    }
    
    class CallLogDataStoreImpl @Inject internal constructor(
        private val contentResolver: ContentResolver
    ) : CallLogDataStore {
    
        override fun getCallLogs(): Array<CallLogEntity> =
            queryAllCallLogs()
    
    interface CallLogRepository {
        suspend fun getCallLogsAsync(): Deferred<Array<CallLog>>
    }
    
    class CallLogRepositoryImpl @Inject internal constructor(
        private val dataStore: CallLogDataStore,
        private val mapper: CallLogMapper
    ) : CallLogRepository {
    
        override suspend fun getCallLogsAsync(): Deferred<Array<CallLog>> =
            GlobalScope.async { dataStore.getCallLogs().map(mapper::mapFromEntity).toTypedArray() }
    }
    any suggestion?
    a
    1 reply · 2 participants
  • m

    mingkangpan

    03/27/2019, 2:24 PM
    I/System.out: RendezvousChannel@6d58005{ReceiveQueued,queueSize=4}
    can anyone elaborate what
    queueSize
    means?
    g
    4 replies · 2 participants
  • p

    paulblessing

    03/27/2019, 2:42 PM
    Is there a suggested approach to cooperative cancellation when calling into code from a coroutine that may not know or care that it's executing inside of a coroutine? The best thought I had was to pass along a facade around the
    Job
    .
    interface ActiveIndicator {
      val isActive: Boolean
      fun ensureActive()
    }
    
    private class JobActiveIndicator(private val job: Job) : ActiveIndicator {
    
      override val isActive: Boolean get() = job.isActive
    
      override fun ensureActive() {
        job.ensureActive()
      }
    
    }
    
    suspend fun doSomething() {
      val job = coroutineContext[Job]!!
      executeCancellableTask(JobActiveIndicator(job))
    }
    
    // (Possibly even in Java code somewhere)
    fun executeCancellableTask(activeIndicator: ActiveIndicator) {
      while (activeIndicator.isActive) {
        // Do some work
      }
    }
    e
    1 reply · 2 participants
  • m

    mayojava

    03/28/2019, 11:46 AM
    What's the recommended way for swapping Default and IO schedulers for UI tests on Android
    s
    i
    4 replies · 3 participants
  • v

    v0ldem0rt

    03/28/2019, 2:50 PM
    Folks I know how to convert
    ExecutorService
    to a coroutine dispatcher. How can I do it the other way around i.e. get ExecutorService from disptacher
    s
    b
    6 replies · 3 participants
  • v

    v0ldem0rt

    03/28/2019, 3:11 PM
    If I have something like
    CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).async {
            // Do some work
        }
    Would this link the scope that I just created to parent scope (i.e. would parent wait)
    a
    s
    +1
    7 replies · 4 participants
Powered by Linen
Title
v

v0ldem0rt

03/28/2019, 3:11 PM
If I have something like
CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).async {
        // Do some work
    }
Would this link the scope that I just created to parent scope (i.e. would parent wait)
a

ahulyk

03/28/2019, 3:13 PM
what do you mean?
launch {
                val data = async(IO) {
                    dataRepository.getData()
                }
                data.await()
}
s

streetsofboston

03/28/2019, 3:17 PM
I don’t think it does. Do this instead to be sure the parent scope’s context is inherited
async(context = <http://Dispatchers.IO|Dispatchers.IO>) {
        // Do some work
    }
v

v0ldem0rt

03/28/2019, 3:18 PM
Actually no, if I don't do await on the Deferred coming back. Would my caller scope wait for child scope to terminate? i.e. Does the async body acts like if I were to launch it in
GlobalScope.async
. I am trying to make it behave like
GlobalScope
g

gildor

03/28/2019, 3:33 PM
No, it will not, there is no Parent/Child relationships, new Job will be implicitly created
You can pass job (or context) from parent scope, but this style is not recommended
v

v0ldem0rt

03/28/2019, 3:59 PM
:thumbsup_all:
View count: 8