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

    tmg

    05/26/2020, 11:16 AM
    Hi guys I’m having trouble with actors, can’t an actor send a message to itself? somehow ,
    channel.send()
    blocks, what’s the properway to do it?
    l
    e
    • 3
    • 11
  • d

    David Glasser

    05/26/2020, 9:35 PM
    I have a List<I> and a mapping function
    suspend (I)->O
    . I’d like to get the
    List<O>
    out, running a bounded number of copies of the mapping function in parallel. I feel like this should be straightforward, eg with Flow, but I can’t quite get it to work
    b
    d
    • 3
    • 10
  • t

    Tash

    05/27/2020, 2:56 AM
    When using a
    callbackFlow
    is it necessary to call
    close(exception)
    if an operation inside it throws? i.e.
    callbackFlow {
       try {
          val result = somethingThatThrows() // Try-catch or just let it be?
          offer(result)
       } catch (exception) {
          close(exception)
       }
       
       awaitClose { ... } 
    }
    d
    • 2
    • 11
  • d

    Dsittel

    05/27/2020, 6:05 AM
    is there a better way to check if a flow is emtpy then,
    flow.count() == 0 ?
    g
    c
    l
    • 4
    • 55
  • k

    kenkyee

    05/27/2020, 11:57 AM
    Nice coroutine speed boost with GraalVM 20.1: https://medium.com/graalvm/graalvm-20-1-7ce7e89f066b
    👍 1
    l
    • 2
    • 2
  • s

    Sean Keane

    05/27/2020, 12:41 PM
    Hi All, I seem to have an issue with Coroutine Exception handler. I have created a scope that accepts a response callback.
    internal class MainScope<T>(private val coroutineContextProvider: CoroutineContextProvider, private val response: (Response<T>) -> Unit) : CoroutineScope {
        override val coroutineContext: CoroutineContext
            get() = coroutineContextProvider.context() + job + exceptionHandler
    
        private val job = SupervisorJob()
    
        //This needs more investigation with thread scope
        private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
            logWarn(throwable.message.orEmpty())
            response.invoke(Response(error = throwable, value = null))
        }
    }
    When an exception occurs I want to capture it and pass it back through the response object.
    class Response<out T>(val value:T?, val error: Throwable? = null) {
    
        fun isSuccess(block: (T) -> Unit): Response<T> {
            value?.let(block)
            return this
        }
    
        fun isFailure(block: (Throwable) -> Unit): Response<T> {
            error?.let(block)
            return this
        }
    
    }
    But the exception handler never gets called when a failure occurs. This is how I launch.
    MainScope(coroutineContextProvider, onResponse).launch { 
     //CODE
    }
    Am I missing something for handling the exception or should it just be captured when an exception occurs
    f
    • 2
    • 3
  • s

    SrSouza

    05/27/2020, 4:21 PM
    Hi folks, anyone that get
    java.lang.VerifyError: Verifier rejected
    using Android Minify (R8) and Coroutines 1.3.6? My current AGP version is
    4.0.0-rc01
    but I was getting the same issue in
    3.6.3
    r
    l
    • 3
    • 3
  • s

    Sam Garfinkel

    05/28/2020, 3:39 PM
    Is there a way to take say a sequence of
    Foo
    , run
    Bar
    on all of the `Foo`s in parallel, then rejoin the results of
    Bar(Foo)
    as an iterable of
    Foo
    in the original order they were given? Suppose
    Bar(Foo)
    will not run the same amount of time per
    Foo
    .
    u
    • 2
    • 2
  • n

    nkiesel

    05/28/2020, 7:56 PM
    We have a function that converts on-disk data into a stream of objects. We have multiple files and wanted to use coroutines to process them concurrently. The solution we came up with looks like this:
    fun readAll(): Stream<Metadata> {
        return runBlocking {
            channelFlow<Stream<Metadata>> {
                Type.supportedTypes.forEach { type ->
                    launch(<http://Dispatchers.IO|Dispatchers.IO> + CoroutineName("Read all for $type")) {
                        send(metadataPersistenceHelper(type).readAll())
                    }
                }
            }.reduce { accumulator, value -> Stream.concat(accumulator, value) }
        }
    }
    (
    Type
    has multiple supported types and
    metadataPersistenceHelper
    does the heavy IO). Does this makes sense or are we abusing coroutines here?
    o
    h
    • 3
    • 20
  • t

    taer

    05/28/2020, 8:14 PM
    Was looking at the benchmark code in the coroutine project. Ran into this.
    fun concat(first: Flow<Int>, second: Flow<Int>): Flow<Int> = flow {
        first.collect { value ->
            return@collect emit(value)
        }
    
        second.collect { value ->
            return@collect emit(value)
        }
    }
    What is the point of the
    return@collect
    ?
    o
    d
    • 3
    • 19
  • s

    Sam Garfinkel

    05/28/2020, 8:45 PM
    How do you “close” a flow? I’m trying to wrap a paginated API call, with ktor, into a flow. I want the flow to emit all pages, and stop emitting once I’ve queried the last page.
    z
    z
    • 3
    • 7
  • e

    EyeCon

    05/29/2020, 12:53 AM
    I'm currently using `Channel`s with a capacity as queues with suspending functions. They are pretty flexible to use with fan-out patterns. Will this still be supported in the future? I read that `Channel`would be deprecated at some point but I'm not sure if this is meant in general, or for specific scenarios.
    d
    e
    • 3
    • 3
  • q

    Quy D X Nguyen

    05/29/2020, 4:56 AM
    Is
    async { suspendFunc() }.await()
    different from
    suspendFunc()
    by itself?
    g
    s
    e
    • 4
    • 14
  • s

    Souhail Marghabi

    05/29/2020, 5:40 AM
    Hello everyone i am currently using channels to handle one time Bluetooth BLE messaging. I have one issue where i use a conflated channel to produce emit only the last updated value. I want to reset/clear the last known value in the channel when the Bluetooth pairing process is done, and i cant seem to find how to reset stored by Channel(.CONFLATED). Any ideas how to do this?
    a
    • 2
    • 2
  • l

    Luis Munoz

    05/29/2020, 7:18 AM
    Spent the last 2 hours trying to figure out why this won't work (won't print anything) when I have newFixedThreadPoolContext(1) but works if I have 2 or more threads.  Can someone explain why that is. Maybe I am not using callbackFlow correctly?
    
    
     
       @Test
        fun `read range`() {
            val ctx = newFixedThreadPoolContext( 1, "tThread") /// test only works if 2 or more
            val scope = CoroutineScope(ctx)
            runBlocking {
                repeat(500) {
                    repo.save("test$it")
                }
                scope.launch {
                    repo.readRange().collect {
                        println(Belief.fromBytes(it))
                    }
                }.join()
            }
        }
        
            fun readRange(): Flow<ByteArray> {
            return callbackFlow {
                database.readAsync { tr ->
                   // reference: <https://apple.github.io/foundationdb/javadoc/com/apple/foundationdb/async/AsyncIterable.html>
                   // will interate all values in the database
                    val itr = tr.getRange(path.range()).iterator()
    
                    // hasNext() is blocking (will do network call and bring back a few items)
                    while (itr.hasNext()) { 
                        sendBlocking(itr.next().value)
                    }
                    channel.close()
                    CompletableFuture.completedFuture(Unit)
                }
                awaitClose { }
            } // end of callbackFlow
        }
    g
    • 2
    • 14
  • l

    Lukas Lechner

    05/29/2020, 2:18 PM
    Kotlin Coroutines: Have you ever wondered if you need to call suspend functions of Retrofit and Room on a background thread? I wrote a blogpost that answers this question! https://www.lukaslechner.com/do-i-need-to-call-suspend-functions-of-retrofit-and-room-on-a-background-thread/
    👍 1
    z
    • 2
    • 1
  • l

    Lilly

    05/29/2020, 2:55 PM
    Hi I'm using a 3rd-party library which processes images asynchronously (Firebase ML kit for text recognition). I store captured images in a list and when I finished capturing I iterate over the list and process it with the text recognition API. The problem I'm facing is that I want to invoke a callback after all images are processed, but I don't know how. Here is my code. Cam someone have a look please?
    Unbenannt
    h
    c
    • 3
    • 11
  • m

    myanmarking

    05/29/2020, 3:24 PM
    hello.currently, is there any way i can use callback flow in which i can call a suspend function in awaitClose ?
    d
    • 2
    • 2
  • s

    spierce7

    05/29/2020, 4:09 PM
    My team mates and I are noticing that a lot of people / blogs discouraging the general use of
    GlobalScope
    . When would it be bad to use
    GlovalScope
    , and when would it be good?
    c
    z
    +2
    • 5
    • 11
  • p

    Pacane

    05/29/2020, 4:14 PM
    I keep hitting those exceptions in one of my scope.launch { } blocks
    kotlinx.coroutines.JobCancellationException: StandaloneCoroutine was cancelled;
    Is there a way to know where this cancellation is coming from? I've put logging+breakpoints everywhere I manually cancel the job, but it's coming from somewhere else..?
    f
    c
    • 3
    • 9
  • r

    Rechee Jozil

    05/29/2020, 8:50 PM
    This is both Android and coroutines specific but think it may apply to more than just Android: I'm trying to come up with a way to have our own "global" scope that can also be replaced with a test coroutine scope for unit tests. Anyone have a recommendation or have sort of implementation like this now? My initial thought is to make the scope injectable via DI (dagger in my case). But not sure if that's overkill vs having some kind of static global scope. Thoughts?
    z
    s
    • 3
    • 11
  • c

    CLOVIS

    05/30/2020, 3:07 PM
    If I understand correctly, there is no ‘nice' way to call suspend functions from JS, Java & other languages. Would it be possible to have a compiler plugin/code generation thing that would create an equivalent of each public suspend function, that wraps it into a
    Promise
    for JS, and an equivalent for other platforms? I'm making a library to access a web service, and it doesn't feel right to add all of those functions by hand, I guess there's a better way?
    s
    r
    • 3
    • 6
  • g

    Gabriel Feo

    05/30/2020, 7:02 PM
    Where is the minimum supported SDK version of coroutines-android stated? Is there such a restriction?
    n
    s
    • 3
    • 3
  • d

    d.medina

    06/01/2020, 3:45 PM
    I am getting a but confused about how suspend works, if i call a none suspend function from a suspend function is it suspendable or do all the functions need to be marked as suspend?
    z
    z
    e
    • 4
    • 4
  • a

    AlexStibbons

    06/01/2020, 6:59 PM
    For someone just getting into coroutines, this might help. I know I really needed it when I was just starting out - so I wrote it 😃 https://medium.com/@alexstibbons/coroutines-an-eli5-glossary-715c5317283d
    🙏 3
    c
    m
    • 3
    • 4
  • t

    Thomas

    06/02/2020, 11:47 AM
    Hi, I am running into an issue with the native-mt version of coroutines. There is an issue about it here: https://github.com/Kotlin/kotlinx.coroutines/issues/1888#issuecomment-635505369 Could someone be so kind to look into this?
    e
    • 2
    • 5
  • l

    Lukas Lechner

    06/02/2020, 11:50 AM
    https://www.lukaslechner.com/how-to-run-an-expensive-calculation-with-kotlin-coroutines-on-the-android-main-thread-without-freezing-the-ui/
    👏 1
    s
    • 2
    • 2
  • d

    Dominaezzz

    06/02/2020, 4:44 PM
    What version of
    kotlinx.coroutines
    does Kotlin playground use? I'm trying to get this (https://pl.kotl.in/fkFVPgVP0) to work.
    • 1
    • 1
  • a

    Albert

    06/02/2020, 5:53 PM
    I am facing issue currently where multiple
    .send
    are done on a channel. At some point we close the channel, but we still have some
    .send
    open. I assumed that
    .close
    would throw an exception or stops suspending for the ones who tries to
    .send
    . But this is not the case. So is it best practise with channel to drain them with
    .consume
    or
    .consumeEach
    ?
    z
    • 2
    • 2
  • t

    taer

    06/02/2020, 10:58 PM
    Quick launch question. I have a method I have to implement. It's called externally, and isn't expected to return till the spawned coroutine exits. I used
    runBlocking
    with great results. But, now I want to use a scope for the class. I have this:
    private val scope = CoroutineScope(serverCoroutineDispatcher )
    
        fun doWork() {
            runBlocking(scope.coroutineContext) {
                //.....
            }
        }
    The runBlocking with the scope's context feels wrong. I could
    scope.launch
    but then it would return instantly. What am I missing?
    o
    h
    l
    • 4
    • 18
Powered by Linen
Title
t

taer

06/02/2020, 10:58 PM
Quick launch question. I have a method I have to implement. It's called externally, and isn't expected to return till the spawned coroutine exits. I used
runBlocking
with great results. But, now I want to use a scope for the class. I have this:
private val scope = CoroutineScope(serverCoroutineDispatcher )

    fun doWork() {
        runBlocking(scope.coroutineContext) {
            //.....
        }
    }
The runBlocking with the scope's context feels wrong. I could
scope.launch
but then it would return instantly. What am I missing?
o

octylFractal

06/02/2020, 11:16 PM
I'd say the most correct thing to do is:
runBlocking(ctx.newCoroutineContext(Job(ctx.coroutineContext[Job])))
basically, create a "child" of the context
hmm, actually, you may not need to do that
it seems like
runBlocking
already creates a child coroutine, at least from static analysis. I'll test it out
h

henrikhorbovyi

06/02/2020, 11:21 PM
When you do:
scope.launch { 
    // your stuff
}
inside your
doWork
function it will return instantly (as you noticed) because your function is not suspend or it is not waiting your launch to be completed
But when you do
runBlocking(scope.coroutineContext) {
  //.....
}
It causes an illusion that doWork is waiting for your process to be completed cause runBlocking blocks your current thread
o

octylFractal

06/02/2020, 11:28 PM
here is my proof for
runBlocking
spawning a child job:
val ctx = CoroutineScope(Dispatchers.Default + SupervisorJob())

fun main() {
    try {
        runBlocking(ctx.coroutineContext) {
            println("I am running...")
            println("But now I will cancel the job by throwing! If I'm not a child coroutine, this _will_ cancel the ctx")
            error("Test error")
        }
    } catch (e: Exception) {
        println("The other runBlocking bailed out: ${e.message}")
    }
    runBlocking(ctx.coroutineContext) {
        println("[A] I will never run if my Job is cancelled.")
    }
    // explicitly cancel now
    ctx.coroutineContext.cancel()
    runBlocking(ctx.coroutineContext) {
        println("[B] I will never run if my Job is cancelled.")
    }
}
results in
I am running...
But now I will cancel the job by throwing! If I'm not a child coroutine, this _will_ cancel the ctx
The other runBlocking bailed out: Test error
[A] I will never run if my Job is cancelled.
Exception in thread "main" kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelled}@3e57cd70
so I believe that what you are doing now is just fine, and will do what you want
l

Luis Munoz

06/03/2020, 2:48 AM
I have code that looks like this this:
suspend fun disconnect(reason: DisconnectReason) {
        withContext(coroutineContext){
            agentConnection.send(Frame().setCommand(Frame.Command.DISCONNECT))
            agentConnection.close(reason)
        }
    }
using runBlocking I think is usually a mistake
when a method suspends you shouldn't hide that
t

taer

06/03/2020, 2:25 PM
In this case, the caller is an old legacy system. They're expecting the method to block until it's complete.
I could make the entry point a runBlocking and then turn around and call a suspend function that uses withContext.. That'd probably work(and expose the "desired" api upstream as well)
My last thing I'm trying to grock is scope vs context.
It just feels weird/wrong to go in and grab the context from the scope
@octylFractal So the throwing exception not canceling is actually what I want. This is inside a backend server where I want to control all jobs spawned for easy shutdown, but not necessarily want the kill server on exception
Actually, that testing brings up a question. When I create
CoroutineScope(serverCoroutineDispatcher)
it creates a Job as part of that if there isn't one already. Then when I runBlocking with that scope that then throws, shouldn't the Job be canceled in that case?
I guess I'm looking for the best way to manage scope/context for a backend server(think webapp server) where each request is independent. Should I have 2 scopes? One per request? And one for background tasks?
Or, I make a beautiful root scope that has a superVisor job, and then create an additional child scope w/ a new Job per request
View count: 5