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

    pardom

    02/26/2019, 4:37 PM
    Anyone have tips on testing coroutines in multiplatform projects?
    runBlocking
    isn’t in common so that can’t be used.
    t
    g
    • 3
    • 5
  • a

    ansman

    02/27/2019, 1:59 PM
    How come
    coroutineScope
    doesn’t accept a
    CoroutineContext
    to merge with the parent context?
    l
    d
    +2
    • 5
    • 17
  • s

    streetsofboston

    02/27/2019, 5:07 PM
    @Jonathan Walsh I have a nagging feeling this could be due to Long overflows, where a MAX_VALUE after a delay (adding to MAX_VALUE) becomes a negative number…. i.e. no delay or waiting…
    j
    • 2
    • 2
  • k

    kevinherron

    02/27/2019, 7:09 PM
    does anybody know the status/plans/roadmap for kotlinx-io?
    e
    • 2
    • 2
  • o

    obobo

    02/27/2019, 7:16 PM
    What's the right way for setting off a 'fire and forget' Job via
    launch
    ? Should I just instance a new scope for the call? Documentation says that any uncaught exceptions will cancel the parent job.
    z
    d
    +3
    • 6
    • 8
  • d

    dewildte

    02/28/2019, 12:07 AM
    I have this crazy error:
    java.lang.NoClassDefFoundError: kotlinx/coroutines/BuildersKt
    	at RandomPanelAction.actionPerformed(RandomPanelAction.kt:17)
    	at com.intellij.openapi.actionSystem.ex.ActionUtil$1.run(ActionUtil.java:220)
    	at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAware(ActionUtil.java:237)
    	at com.intellij.ide.actions.GotoActionAction.lambda$performAction$7(GotoActionAction.java:352)
    	at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:88)
    	at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransaction$1(TransactionGuardImpl.java:111)
    	at com.intellij.openapi.application.TransactionGuardImpl.submitTransaction(TransactionGuardImpl.java:120)
    	at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransactionLater$4(TransactionGuardImpl.java:271)
    	at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.doRun(LaterInvocator.java:447)
    	at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:431)
    	at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:415)
    	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:762)
    	at java.awt.EventQueue.access$500(EventQueue.java:98)
    	at java.awt.EventQueue$3.run(EventQueue.java:715)
    	at java.awt.EventQueue$3.run(EventQueue.java:709)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:732)
    	at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:781)
    	at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:722)
    	at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:382)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    Caused by: java.lang.ClassNotFoundException: kotlinx.coroutines.BuildersKt PluginClassLoader[IntelliGlo.intelliglo-plugin, 0.0.1] com.intellij.ide.plugins.cl.PluginClassLoader@6d3678f6
    	at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:63)
    	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    	... 28 more
    d
    • 2
    • 2
  • s

    sitepodmatt

    02/28/2019, 3:36 AM
    Is there a way to get the parent Job from coroutinecontext's Job without using reflection to get privates?
    g
    • 2
    • 12
  • s

    sitepodmatt

    02/28/2019, 7:46 AM
    @elizarov is there a reason Job doesn't expose parentJob : Job?. My use case would be logging/debugging aids - wanting to log the path of jobs to the root when one fails, a job trace vs a stack trace. Ive managed to hack around it with this evil code but I wondering if there a strong reason for concealing
    @UseExperimental(InternalCoroutinesApi::class)
    fun Job.getParent() : Job? {
        return (AbstractCoroutine::class.java as Class<*>)?.
            getDeclaredField("parentContext")?.
            also { it.isAccessible = true }?.
            let { it.get(this) as? CoroutineContext? }?.
            let { it[Job] }
    }
    e
    • 2
    • 5
  • s

    sitepodmatt

    02/28/2019, 10:20 AM
    class RequestContextTest : StringSpec({
        "playing with human context" {
    
            runBlocking {
    
                supervisorScope {
    
    
                    try {
                        val repoSize = async<String> {
                            // do remote
                            val somenestedOp = async<String> {
                                delay(100)
                                throw DomainException("oh no", Exception("400"))
                            }
                            somenestedOp.await()
                        }
    
                        repoSize.await()
                    } catch (de: DomainException) {
                        println("we will swallow")
    
                    }
    
    
                }
    
    
            }
            println("we exited okay")
        }
    
    
    })
    
    class DomainException(msg: String, t: Throwable) : Exception(msg, t)
    l
    • 2
    • 9
  • l

    louiscad

    02/28/2019, 11:15 AM
    Hi, I'm working again on Android's callback hell based Camera2 API, resuming work on an open source library to implement structured concurrency in the bast possible way. My questions are the following: 1. How to cancel a scope (based on an error callback) with a specific exception? In my case, in a local
    coroutineScope { ... }
    , I have an
    async
    block that needs to be cancelled if some error callback comes in, and that exception coming in is the cause of the cancellation, so
    CoroutineScope.cancel()
    doesn't suit my needs. 2. Is using
    CompleteableDeferred<T>(coroutineContext[Job])
    safe? My guess is that it will cancel the scope with the proper exception if its
    completeExceptionnaly(…)
    function is called, and it will itself be cancelled if the scope is cancelled from another place. Am I right about this? If so, I'm wondering why there's no
    completableDeferred<T>()
    extension function for
    CoroutineScope
    that would do it without needing to pass
    coroutineContext[Job]
    .
    d
    • 2
    • 1
  • d

    Dias

    02/28/2019, 12:41 PM
    Hi, let's say I have 3 coroutines: A,B and C. I want A and B be related, as in when A fails B cancels as well, and vice-a-versa. I also want C depend on A and B, but only one direction, so A and B failure would cancel C, but not other way around. There is probably simple way to do it, but I am confused now. I know of supervisor scope, but that makes all children equally unrelated, while I have some sort of downward hierarchy: PARENT / \ A - B \ / C
    g
    • 2
    • 2
  • m

    Martin Devillers

    02/28/2019, 2:19 PM
    I’m running into some difficulties when trying to process items in parallel with coroutines. My current scenario is that I have a large collection of items, and I need to do a CPU-consuming transformation on each of them (deciphering data, if you’re curious). As I process these items, I want to broadcast the progress, which is the count of the number of items processed. My idea was that after each item is processed, it would send a
    Unit
    to a channel, which would count the number of items received and update that information. The items are processed by simply mapping the list to
    async
    calls which process the item then
    send
    to the progress channel, then doing
    awaitAll
    on this channel. See the code. The issue I’m running into is that the progress isn’t being broadcast along as items are processed. Instead, all the items are processed, then all the progress updates are sent, which isn’t very useful. As I understand it, this is because the dispatcher’s queue is “fair”, therefore it handles all the
    async
    calls before handling the
    receive
    calls of the actor. If you have ideas on a better way to do this, I would really appreciate it. One solution that I see is to use the “fan-out” technique described in the coroutine guide, but this seems weird to me since I have a list, not a channel, and also because I lose the benefit of leaving the responsibility of determining the parallelism of processing to the coroutine dispatcher. Thanks 🙂
    -.kt
    d
    d
    • 3
    • 37
  • r

    rrva

    02/28/2019, 4:20 PM
    Want to advertise a light-weight server microframework for HTTP services we've been using in production for over a year: Jooby. 1.x has been around for many years and to my mind has a great balance between noninvasiveness (you can easily move off jooby as a framework should you decide to do so), productivity and lightness, but still with great basic feature set. It also has a nice Kotlin DSL for HTTP routes. Tastefully built in my opinion, and you go for a more annotation/injection free style of programming for microservices where application logic code can be given a greater focus because the rest "never gets in the way". Good set of plugins for common use cases. Now 2.x is under development, and a notable feature is Kotlin coroutine support 1.x: https://jooby.org/ (We've been using it for over a year in production) 2.x: https://jooby.io/ (Now with Kotlin coroutines)
    👍 3
    k
    d
    • 3
    • 2
  • r

    Ryota

    03/01/2019, 2:17 AM
    Hi folks - I’m sorry for a newbie question, but my research didn’t conclude in clear understanding of
    runBlocking
    usages and I’d love to get some pointer. My goal is to start a blocking process with AWS Lambda, which would kick off a bunch of heavy tasks concurrently, and then returns the aggregate of the tasks when they are all completed (or when any canceled). Because the Lamdba interface itself is not a suspending function (i.e.
    RequestHandler<I, O>
    interface needs function with signature of
    public O handleRequest(I input, Context context)
    ), I will need a coroutine builder inside
    handleRequest
    method to await for the tasks. I have read in a few places how
    runBlocking
    is only meant to be used for unit testing mainly, and should not be used in production. What I want to achieve seems to require
    runBlocking
    for good reason, but I am unsure if I’m missing something obvious. Given serverless function requiring a blocking call, is
    runBlocking
    a legitimate approach in this scenario? Or is there something that I’m missing? Thanks in advance for your support!
    g
    g
    • 3
    • 4
  • j

    jw

    03/01/2019, 2:38 AM
    yep. i usually put the loop in a method to be the worker and then do 9 launch/asyncs and one "synchronous" call of it.
    d
    • 2
    • 1
  • s

    serebit

    03/01/2019, 3:10 AM
    Well that’s interesting! Adding
    coroutineScope
    or
    supervisorScope
    to one of my suspend functions not only stops the build, but breaks the Kotlin compiler completely!
    :youtrack: 1
    e
    • 2
    • 4
  • d

    Davide Giuseppe Farella

    03/01/2019, 12:58 PM
    Hello, this is my code flow from DB to ViewModel, I can’t figure out why my Use Case’s `Channel`s don’t emit anything:
    • 1
    • 1
  • d

    Davide Giuseppe Farella

    03/01/2019, 1:08 PM
    TLDR; this is what worries me more, is there anything wrong here?
    override suspend fun observeCount() = coroutineScope {
        queries.count().asChannel().mapToOne( coroutineContext ).map { it.toInt() }
    }
    l
    • 2
    • 18
  • l

    louiscad

    03/01/2019, 2:37 PM
    Contracts for suspending functions! That means we will get it in
    withContext
    and
    coroutineScope
    at some point!
    😒uspend: 8
    🎉 1
    • 1
    • 1
  • m

    marcoferrer

    03/01/2019, 5:02 PM
    I was trying something like this but noticed that the exception is already unwrapped at this point.
    coroutineContext[Job]?.invokeOnCompletion {
            if(it is CancellationException){
                call.cancel(it.message,it.cause ?: it)
            }
        }
    w
    d
    • 3
    • 4
  • o

    otakusenpai

    03/01/2019, 6:15 PM
    How do I include kotlinx.coroutines.experimental ? In my project, which I'm starting from new
    z
    l
    g
    • 4
    • 11
  • a

    ansman

    03/01/2019, 10:14 PM
    I was pretty surprised that a coroutine scope won’t complete if there are any unstarted coroutines in it. This function will never return for example:
    coroutineScope {
      launch(start = LAZY) {}
    }
    b
    l
    g
    • 4
    • 16
  • a

    asad.awadia

    03/01/2019, 11:55 PM
    @elizarov hey Roman - can we get a post or a video on idiomatic use of kotlin coroutines? Rob pike has one for go and it seems like a really good way of suggesting patterns for real world usages
    ➕ 2
    l
    e
    • 3
    • 8
  • m

    Matej Kormuth

    03/02/2019, 3:14 PM
    Hi, I launch a coroutine with
    while(true) { ... delay(3000) }
    code in it. Is is possible to somehow trigger skip of the delay (waiting 3s) and run the while loop body immediately?
    d
    e
    • 3
    • 4
  • a

    asad.awadia

    03/03/2019, 6:42 AM
    And i get into the foreach lambda for the result set I cant call send on a channel?
    d
    • 2
    • 1
  • a

    asad.awadia

    03/03/2019, 7:25 AM
    I can’t come out of reading a channel loop? Its a hard block on the execution?
    g
    v
    g
    • 4
    • 28
  • b

    bogdoll

    03/03/2019, 6:27 PM
    How would a SuspendingQueue analog to a BlockingQueue look like? Are there some example sources for that available?
    d
    • 2
    • 2
  • a

    aksh1618

    03/03/2019, 7:09 PM
    On trying to run this code in playground: https://pl.kotl.in/r1dZNoYIE, it says "No main method found in project". However, on uncommenting
    await()
    on both, it runs. Is this a bug with the playground?
    g
    b
    +2
    • 5
    • 6
  • g

    groostav

    03/03/2019, 7:39 PM
    I'm trying to get a good grip on the result using
    Unconfined
    to try and keep stacks neat. Namely I'd like to use an unconfined consumer to keep the producer on the stack trace, But I think there's a races making my life hard. AFAIK the contract with unconfined is so weak (and is aimed at performance, not debugability) that perhaps this isn't a bug per se, but Id still like to see it. Proof-of-concept: https://gist.github.com/Groostav/f8ef01ed830c14c394ac5b992d981aa1 if you put a breakpoint on
    send
    and walk-through the the downstack implementation it will eventually invoke the receiver
    , If you just run the test, on my machine, the
    runBlocking
    event loop will invoke the receiver.
    v
    • 2
    • 3
  • a

    Alexjok

    03/04/2019, 9:16 AM
    Hello to all! How can I define an interface for this method
    suspend fun CoroutineScope.removeDuplicateTerminal(objectId: MutableList<Int>, token: String) = async { }
    a
    t
    • 3
    • 8
Powered by Linen
Title
a

Alexjok

03/04/2019, 9:16 AM
Hello to all! How can I define an interface for this method
suspend fun CoroutineScope.removeDuplicateTerminal(objectId: MutableList<Int>, token: String) = async { }
a

antonis

03/04/2019, 9:24 AM
Hello. I don’t think an extension function can be extracted in an interface
What is your use case?
a

Alexjok

03/04/2019, 9:27 AM
I use it in spring and want to make an autowired implementation through the interface.
a

antonis

03/04/2019, 9:28 AM
It seems that I’m wrong. This looks valid
interface YourInterface { suspend fun CoroutineScope.removeDuplicateTerminal(objectId: MutableList<Int>, token: String) } class YourClass: YourInterface { override suspend fun CoroutineScope.removeDuplicateTerminal(objectId: MutableList<Int>, token: String) { } }
a

Alexjok

03/04/2019, 9:45 AM
Thank! I hurried with the question 🙂
suspend fun CoroutineScope.removeDuplicateTerminal(objectId: MutableList<Int>, token: String): Deferred<Unit>
👍 1
t

tseisel

03/04/2019, 4:16 PM
If your function starts a coroutine that doesn't need to return a result, you may consider returning a
Job
instead of
Deferred<Unit>
, replacing
async
with
launch
. You can then
job.join()
to wait for the coroutine to complete its work.
👍 1
a

Alexjok

03/04/2019, 5:27 PM
Yes, you are right! Thank you
View count: 2