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

    evan

    01/18/2019, 8:54 PM
    Hello, I'm using IntelliJ to try out coroutines on the JVM. I have a pretty simple method that calls
    GlobalScope.launch
    , awaits a deferred value, prints its contents, and then outside of the launch method, prints a concluding String. All of this is working great. The process is still running when these two print tasks complete however. What is keeping it alive, and can I gracefully shutdown when all my work has been completed? Edit: Updated code block from Louis' comments
    suspend fun main() {
        val api = createRestApi<RestApi>("<https://catfact.ninja/>", okHttpClient(), moshi)
    
        coroutineScope {
            val facts = api.getFacts().await()
            println(facts.data)
        }
        println("That's all")
    }
    l
    s
    • 3
    • 4
  • a

    altavir

    01/19/2019, 9:10 AM
    @Ilmir Usmanov [JB] I've looked up
    runTest
    and sadly, it does not solve the problem with "blocking" calls in JS (also it could be run only from test). I am still thinking if it is really necessary. My use case is that I have an interface with a regular blocking function and implementation which utilizes coroutines for parallel computations. Currently I can't do it since I can't collect parallel elements in a non-blocking way. Maybe there are better ways.
    i
    v
    • 3
    • 9
  • o

    otakusenpai

    01/20/2019, 9:59 AM
    Hey guys, I have a function inside a coroutinescope which I need to call every few seconds. How do I do that? It's a timer kind of thing.
    o
    d
    • 3
    • 14
  • d

    Dmytro TOLSTYI

    01/21/2019, 7:59 AM
    Hi guys. I got a strange situation with
    suspend
    function which I can't solve: I got function
    suspend fun one()
    which executes some code and then calls a function that accepts a callback function as a param. But, this param function is not suspend. The issue is that I need to call another suspend fun from that callback param function. Here's an example:
    suspend fun one() {
        doSomething()
        funWithNonSuspendCallback("data") {
            two() // I need to call it from here but this is not suspend scope anymore
        }
    }
    
    suspend fun two() {
    }
    u
    l
    • 3
    • 18
  • g

    ghedeon

    01/21/2019, 12:47 PM
    Trying to understand why it's never completed:
    fun main(){
        runBlocking{
        	foo().consumeEach{ println(it) }
        }
    }
    
    suspend fun foo(): ReceiveChannel<Int> = coroutineScope {
        produce<Int>{
    		channel.send(42)
                   channel.close()
        }
    }
    m
    g
    • 3
    • 7
  • s

    simon.vergauwen

    01/21/2019, 1:12 PM
    Is it not possible to recover from a failed
    Deferred<A>
    ? I was expecting to be able to define a
    handleErrorWith
    operator that wraps an existing
    Deferred
    to recover from errors but the program results in the original error.
    a
    l
    • 3
    • 14
  • l

    louiscad

    01/21/2019, 3:05 PM
    Is kotlinx.coroutines debug not supported on Android? I tried to call
    DebugProbes.install()
    but got this runtime exception: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
    v
    w
    e
    • 4
    • 6
  • e

    elizarov

    01/21/2019, 8:55 PM
    Is
    select { deferreds.forEach { it.onAwait { it } } }
    elegant enough?
    💯 4
    ➕ 1
    c
    m
    • 3
    • 3
  • g

    ghedeon

    01/21/2019, 11:45 PM
    Is there any special trick about breakpoints in coroutines? The test is green, but the breakpoint point doesn't stop:
    @Test
        fun test() {
            runBlocking {
                val channel = produce<Int> { channel.send(42) }
                channel.consumeEach { assertEquals(42, it) } // <--- break point is on this lambda
            }
        }
    P.S. I'm using
    Dispatchers.setMain()
    on android
    s
    e
    • 3
    • 4
  • j

    judrummer

    01/22/2019, 4:06 AM
    I want to create extension to convert Promise type
    g
    • 2
    • 3
  • j

    judrummer

    01/22/2019, 4:06 AM
    First_way.kt
    g
    • 2
    • 1
  • j

    judrummer

    01/22/2019, 4:07 AM
    Second_way.kt
    g
    • 2
    • 2
  • j

    judrummer

    01/22/2019, 4:08 AM
    Which way is correct to make my suspend coroutine to be in same scope for calling coroutine scope?
    g
    • 2
    • 4
  • g

    ghedeon

    01/22/2019, 10:40 AM
    Any rough estimations from officials of when Channels are going to be production ready? The quarter of the year maybe. (Note: it's not about push or faster delivering, it's about roadmaps and planning)
    d
    v
    z
    • 4
    • 21
  • a

    amadeu01

    01/22/2019, 2:44 PM
    hi guys, when channels will be a stable feature?
    🤦‍♂️ 3
    😂 2
    g
    v
    • 3
    • 3
  • d

    Drew

    01/22/2019, 4:39 PM
    I have a simple question regarding coroutines, if anyone could help me. I must be missing something... Kotlin MPP project, using following dependencies, I am unable to resolve
    runBlocking
    at all:
    commonMain.dependencies {
                implementation 'org.jetbrains.kotlin:kotlin-stdlib-common'
                implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.9.1"
                implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0'
                implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core-common:1.1.0'
            }
    
            androidMain.dependencies {
                implementation 'org.jetbrains.kotlin:kotlin-stdlib'
                implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.0'
            }
    
            iosMain.dependencies {
                implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:0.9.1"
                implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core-native:1.1.0'
            }
    Also, using Kotlin 1.3.11
    v
    • 2
    • 2
  • g

    gumil

    01/22/2019, 9:01 PM
    How do you test coroutines started with
    launch
    ? If I understand correctly
    launch
    always run asynchronously and in tests we would like to run it sequentially.
    a
    g
    d
    • 4
    • 23
  • a

    Allan Wang

    01/23/2019, 4:27 AM
    If I have a suspend function that does nothing but change contexts, how do I ensure that I catch any failures and ensure that my logic continues? My parent scope is already a supervisor job, and I try catch my suspended calls. However, I notice that I need to do so multiple times to ensure that I actually catch errors After some tests, I can use a
    supervisorScope
    and try catch it. However, it still doesn’t stop the cancellation of every other job, despite the main context already being a supervisor
    d
    • 2
    • 5
  • x

    xyma

    01/23/2019, 6:09 AM
    Is there any way to get the in flight & finished task count of
    <http://Dispatchers.IO|Dispatchers.IO>
    ?
    v
    • 2
    • 4
  • j

    julioyg

    01/23/2019, 10:58 AM
    it says there is an error processing
    kotlinx-coroutines-debug
    but we don't have that module listed in our gradle file 🤔
    v
    • 2
    • 8
  • b

    bobby

    01/23/2019, 11:30 AM
    Hi all, does coroutines (or continuations) have some kind of "hooks" that we can attach to on resume? Basically I want to intercept the resumption of continuations to do some custom behavior before actually resuming. I hope this question makes sense to you.
    s
    v
    • 3
    • 10
  • s

    spierce7

    01/23/2019, 4:21 PM
    Has there been any news about cold streams for coroutines?
    e
    z
    • 3
    • 5
  • r

    raulraja

    01/24/2019, 2:53 PM
    The
    @RestrictSuspension
    annotations does a great job and has proven very useful for controlling side effects in Arrow. Kudos to everyone involved with the suspend system! The only problem I'm having is that the compiler error messages for restricted contexts are not very useful. They just state the arbitrary suspended function can't run there. I would like to customize such error messages a la carte to provide reasons why functions are restricted in a suspended receiver. For example:
    save() can't be invoked in this [UI] scope because is scoped to [DB]
    Is there a way to customize such error messages? If not is this something that would change in the compiler or std lib?
    e
    • 2
    • 2
  • m

    Marc Knaup

    01/25/2019, 9:56 AM
    Didn't know
    @RestrictSuspension
    ! What is it good for? Is there an article about it? 😮
    o
    e
    r
    • 4
    • 5
  • i

    irus

    01/25/2019, 11:23 AM
    private val topics = mutableMapOf<String, Publisher>()
        private val lock = Mutex()
    
        suspend fun method(key: String) {
            lock.withLock { 
                topics.getOrPut(key) { //... }
            }
        }
    is lock gives guarantee that other coroutines will see changes in
    topics
    ?
    g
    d
    e
    • 4
    • 14
  • s

    streetsofboston

    01/25/2019, 5:55 PM
    The documentation says that only
    launch
    will use the CoroutineExceptionHandler
    For
    async
    , the exception is thrown when using
    await()
    a
    n
    • 3
    • 6
  • j

    josephivie

    01/25/2019, 9:03 PM
    Just to clarify my understanding after reading a bunch of documentation: if we want a property that anybody can observe, we would use
    ConflatedBroadcastChannel
    , correct?
    g
    • 2
    • 2
  • j

    jossiwolf

    01/26/2019, 12:11 PM
    Hi! I am trying to call a
    suspend fun
    from Java, but I can't access any properties of
    Result
    - when implementing
    Continuation
    , I only get an
    Object
    in
    resumeWith
    . Can anybody help with that? 🙂
    m
    d
    • 3
    • 30
  • m

    Marc Knaup

    01/27/2019, 8:18 PM
    Yeah, but I'd like to avoid making a whole JSON library suspend 😄 And try…finally will make the logic really complex because you cannot wrap a code into a lambda anymore and it will affect plenty of functions 😞
    l
    • 2
    • 7
  • a

    Alexjok

    01/28/2019, 7:56 AM
    Hello! How can I declare a function
    override suspend fun save(something: Something) = withContext(Dispatchers.Default) {
       doWork()
    }
    in the interface?
    g
    • 2
    • 3
Powered by Linen
Title
a

Alexjok

01/28/2019, 7:56 AM
Hello! How can I declare a function
override suspend fun save(something: Something) = withContext(Dispatchers.Default) {
   doWork()
}
in the interface?
g

gildor

01/28/2019, 7:58 AM
interface Savable {
   suspend fun save(something: Something)
}
a

Alexjok

01/28/2019, 8:08 AM
brrr, sorry for the stupid question... Intellij underlined in red because the
save
method in
jpa model
returns the saved object. I need a cup of coffee 🙂
g

gildor

01/28/2019, 8:10 AM
ah, yeah, you have to specify also return type if doWork() has it
View count: 8