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

    rook

    11/01/2018, 8:26 PM
    I just want to stop the single one I’m in. I’ll use
    return@launch
    , thanks
    l
    • 2
    • 2
  • n

    nwh

    11/01/2018, 9:48 PM
    Does
    withContext
    create a new (child) scope?
    l
    • 2
    • 1
  • m

    mp

    11/02/2018, 4:39 PM
    what do you mean “before”? You mean on the enclosing function?
    m
    • 2
    • 3
  • j

    javad

    11/02/2018, 4:48 PM
    Is there a library to provide extension functions for RxJava 1 types? Like
    Single.await()
    ? The official lib only supports RxJava 2 😞
    j
    z
    g
    • 4
    • 12
  • d

    Dias

    11/02/2018, 5:52 PM
    when I run GlobalScope.launch, is it backed by a threadpool? or it will run in the main thread?
    e
    • 2
    • 3
  • m

    marcelo

    11/02/2018, 10:11 PM
    maybe using
    async
    and
    await
    ?
    j
    f
    n
    • 4
    • 12
  • z

    Zach Klippenstein (he/him) [MOD]

    11/02/2018, 10:35 PM
    @elizarov I feel like I recently read/watched you say somewhere recently that you recommended a convention for coroutine functions, something like “if a function is
    suspend
    , it shouldn’t block the current thread”. Do you remember where that was (if it was in fact something you did say)?
    m
    • 2
    • 2
  • n

    nwh

    11/03/2018, 12:13 AM
    Within a body of a
    suspend
    function, shouldn't the current
    CoroutineScope
    be accessible? Since it had to be invoked from some type of scope?
    l
    m
    +2
    • 5
    • 10
  • n

    nulldev

    11/03/2018, 9:20 PM
    Nevermind, actually solved this in a very nice way using
    select
    on
    send
    . I just allocated an output and input channel for each worker:
    suspend fun invoke(input: InputType): OutputType {
            return selectUnbiased {
                for(worker in runningWorkers) {
                    worker.inputChannel.onSend(input) {
                        worker.outputChannel.receive()
                    }
                }
            }
        }
    z
    • 2
    • 1
  • d

    DALDEI

    11/04/2018, 3:46 AM
    Any recommendations to 'generically' (or 'generally', not referring to 'generics') have ThreadLocal variables follow the execution of a co routine that is dispatched to a different thread. I know I can do it with a custom dispatcher (I think -- haven tried yet) -- but this seems like a common design pattern.. Example in this case is log4j thread context stack and maps (CDC,MDC) -- the desired end-state is a way to bind the call stack affinity of functions - co-routines or not - with the common java convention of using ThreadLocal to do that. Of course while NOT breaking other reasons for using ThreadLocal which have no relation to call stack. Something like a XSLT with-param. The 'new' coroutine scopes are similar but they have been very 'brittle' for me as they require (in ways non-obvious to me) that the scope is lexical -- so if you call a function it loses track of the current scope. I understand some of the rationale for this -- but its actual use can be very subtle and cause difficult to debug errors. similarity is thread context variables, especially from 'third party' Java libraries - which reasonably assume that threads will not change if you are in the same call stack ( and don't hand a lambda off to a thread ... ) It seems that there is or could be some kind of library or convention to express this easily. These two language features/problems are similar in several ways -- analogous solutions in the java world include variants on conventions how class loaders are searched -- although those are fraught with inconstant or non-obvious convention differences as well -- including kotlin scripting where its more then non-obvious WTF class loader a compiled or invoked script will inherit. A general concept of how one manages non-local Affinity consistently would be very useful. Many frameworks resort to the classic 'pass a context variable to every function' to solve this. I have yet to find anything 'better' -- but even that convention fails unless you are in control of 100% of the source -- and happy to add yet another argument to every function in your app.
    e
    • 2
    • 2
  • k

    Kulwinder Singh

    11/04/2018, 9:47 AM
    how to make this call parallel , where
    init
    and
    getLastState
    are
    suspend
    function ?
    How_to_do_parallel__.kt
    l
    d
    b
    • 4
    • 9
  • a

    acando86

    11/04/2018, 4:19 PM
    Question about unit testing. Most of my android code only relies on suspend functions idiomatically, without coroutine builders, and that causes no problems with tests. The builders (mainly, withContext or sometimes launch) are primarily used only by the end consumers of my business logic (eg, the UI presenters) .. Before structured concurrency, i was used to inject from outside the coroutine contexts in the presenter constructor , so in the main application i was passing UI/IO instances of coroutine contexts say, and in the tests i was passing an instance of something suitable for tests (typically, Unconfined). Now, after structured concurrency migration, i originally made my presenters receive coroutinescope and the IO context from outside, but I’m pretty sure there’s a better way to handle this. What's the best way to translate this kind of tests to structured concurrency? How do you usually express these tests? Thank you
    👍 1
    z
    g
    • 3
    • 2
  • l

    louiscad

    11/05/2018, 9:36 AM
    Hi, I want to use the
    select
    clause to select between two user inputs (two button clicks). Should I implement the select clause myself in an extension function, or should I transform the button clicks to a channel, and then use the already existing select clause implementations?
    g
    g
    +2
    • 5
    • 22
  • a

    aaverin

    11/05/2018, 10:47 AM
    Hey everybody! Wasn’t there a converter from Coroutines to RxJava1? I can’t seem to find it, I thought it will be here https://github.com/Kotlin/kotlinx.coroutines/tree/master/reactive
    e
    g
    +2
    • 5
    • 18
  • t

    Tolriq

    11/05/2018, 10:59 AM
    After a few discussions it seems that the consensus for limiting threads for certain purpose should be coroutine worker pool. In an attempt to improve my internals I'd like to migrate my bad situation that is a mix of synchronous code, callbacks and futures in a dedicated thread pool to coroutines. The application can communicate with different systems that each have their specific limitation needs. And the main application should be unaware of that. The goal is to move to fully suspend functions, but with each system being able to enfore some global limits on all the called functions.
    interface Host {
    
       suspend fun getMovies() : List<Movies>
       suspend fun setWatched(movie:Movie) : Boolean
       
       .....
    }
    Imagine a lot more functions. At any given moment there should be no more than X functions running. Ideally the limit should only apply to the actual server communication and the transformation of received data, should not be limited to allow faster command enqueing. The interface does implement close() that should also cancel all running coroutines for the host. My solution with blocking calls, would be to have a dedicated thread pool as dispatcher and use withcontext for the network call, but this is not efficient and no more works if some of the calls are non blocking and can switch to IO for example. I'd really appreciate some help on how to apprehend this needs, as it's major refactoring so needs to be done correctly 🙂
    j
    z
    • 3
    • 8
  • j

    julioyg

    11/05/2018, 11:48 AM
    Hi: if I got a function like
    fun doSomeStuff() : Deferred<String> = async { /*doing something*/}
    , should that be an extension function of a
    coroutineContext
    as it starts a coroutine?
    g
    • 2
    • 6
  • w

    wcaokaze

    11/05/2018, 11:59 AM
    launch {
        try {
            async { throw IOException() }.await()
        } catch (e: IOException) {
        }
    }
    I get an uncaught IOException. What is wrong?
    j
    • 2
    • 7
  • j

    Jaroslav

    11/05/2018, 1:40 PM
    I’m refactoring one interface to change function from suspend to simple. Any ideas how this can be done? Current:
    Inteface T { suspend fun A: String}
    
    Class S{
      suspend fun B(){
        val result = t.A() 
    }
    }
    I want to change fun A to return Deferred<String> object, but not sure how to change
    val result = t.A()
    so the result would be the same as if A was suspend function.
    j
    z
    • 3
    • 5
  • m

    marcelo

    11/05/2018, 2:08 PM
    Not sure how can I call my code within a non-suspend function and still return it. Here I am adding the
    renderMetricTimer.tagVal(renderTemplate.mediaType.name).time {
    but clearly it gives the error
    suspend function needs to be call in a subroutine.
    This function returns a value (
    map
    ). Not sure how can I do this.
    -.php
    z
    • 2
    • 1
  • m

    marcelo

    11/05/2018, 2:20 PM
    unless I have to do this:
    return templates.map { renderTemplatePath -> 
      runBlocking {
        val result = async {
          renderMetricTimer.tagVal(package).time {
            //code
          }
        }
        result.await()
     }.toSet()
    }
    Obviously, I am new to coroutines, but this seems like a lot of coroutine builders, no?
    s
    n
    • 3
    • 8
  • o

    oshai

    11/05/2018, 3:26 PM
    I want to create an integration module for our async lib, right now it is using
    CompleteableFuture
    . So I thought about converting it to either
    suspend fun
    by using the
    await
    extension. Another option is to create methods that return
    Deferred
    . What do you think is a better approach?
    z
    d
    g
    • 4
    • 37
  • l

    littlelightcz

    11/05/2018, 6:10 PM
    I am not sure if this hasn't been already asked before, but can a deeply nested child coroutine call
    cancel()
    on the outermost parent's
    Job
    ?
    g
    • 2
    • 5
  • m

    marcelo

    11/05/2018, 6:11 PM
    Trying to get this coroutines. On this code. Why do I have to specify
    return@time
    ? Is it because my suspended coroutine is called time? Also, why can't I do the following:
    return when(process.exitValue()) {
      0 -> {
             return resultsAdapter.fromJson(scanResults)
    ...
    }
    -.php
    l
    k
    • 3
    • 6
  • d

    droidrcc

    11/05/2018, 6:22 PM
    Probably has already been asked. Shouldn’t be always preferred to use withContext() instead of launch() ?
    v
    g
    • 3
    • 5
  • s

    Steven McLaughlin

    11/05/2018, 9:05 PM
    Had a friend ask this:
    how do kotlin coroutines work? i.e. is it just a state machine on top of Java's threadpool?
    I don't really know anything about the internals. I thought maybe someone in here would have some insight
    d
    v
    k
    • 4
    • 7
  • n

    nwh

    11/05/2018, 9:38 PM
    Is there any "guide" on knowing which scope to pick when launching a coroutine? I'm not sure what exactly I should be basing that decision off of. For example, if I'm launching something that isn't directly relevant to a lifecycle, should I only use
    GlobalScope
    , or should I use the most localized scope I can, just so the processes stay organized?
    d
    • 2
    • 1
  • n

    nwh

    11/05/2018, 9:43 PM
    Also, in what situation is a
    CoroutineScope
    not used for what is essentially an on-going
    Job
    with a lifecycle? That's how I've always thought about it (I believe it was mentioned in a kotlinconf talk)
    z
    • 2
    • 1
  • k

    karelpeeters

    11/05/2018, 10:06 PM
    Well this works, feels bad though:
    private val loop = iterator {
        for (i in 0 until 10) {
            println(i)
            yield(Unit)
        }
    }
    
    fun doIteration() {
        loop.next()
    }
    n
    d
    e
    • 4
    • 8
  • v

    vitrox1

    11/06/2018, 8:42 AM
    Hello, after updating to 1.3 my build get stucked and as far i can see, it seems the thread of coroutines remain hanging in, and never stop, is something related with the scope or should i check somewhere else?
    COROUTINES_BAMBOO_ERROR.txt
    g
    • 2
    • 2
  • d

    devbridie

    11/06/2018, 12:22 PM
    I also have the same problem that my program will never terminate when using
    suspend fun main() {}
    .
    e
    • 2
    • 1
Powered by Linen
Title
d

devbridie

11/06/2018, 12:22 PM
I also have the same problem that my program will never terminate when using
suspend fun main() {}
.
e

elizarov

11/06/2018, 12:41 PM
Can you give a snippet of code that shows it?
View count: 2