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

    Paul Woitaschek

    11/24/2020, 8:16 AM
    Can someone confirm that this crashes in kotlin 1.4.20 with a VerifyError?
    import kotlinx.coroutines.runBlocking
    
    fun main() {
        val getTrainingEmoji = GetTrainingEmoji()
        runBlocking {
            getTrainingEmoji()
        }
    }
    
    inline class Emoji(val value: String)
    
    class GetTrainingEmoji {
    
        suspend operator fun invoke(): Emoji {
            return Emoji("hello")
        }
    }
    w
    • 2
    • 5
  • w

    wbertan

    11/24/2020, 3:34 PM
    Hello, I’m trying to use
    StateFlow
    to handle a kind of
    Event
    , but facing issues when trying to set the same value again (for example when the user clicks the same button again, triggering same event). Found this GitHub issue: https://github.com/Kotlin/kotlinx.coroutines/issues/2011 With @elizarov comment:
    We'll provide a different, more flexible primitive, for those rare cases when you don't want equality-based conflation. Stay tuned.
    Do we have anything in the latest release to handle this scenario?
    b
    • 2
    • 5
  • a

    André Thiele

    11/24/2020, 4:19 PM
    Is it ok to handle one-time events with a SharedFlow instead of the LiveData + Event class approach?
    a
    • 2
    • 7
  • f

    Florian

    11/24/2020, 5:27 PM
    What do I need to do in here in terms of closing/cancellation/throwing? This is so confusing. Do I need to close the Flow? Cancel the coroutine? Anything else?
    inline fun <reified T> Query.asFlow() = callbackFlow<List<T>> {
        val registration = addSnapshotListener { snapshot, error ->
            if (error != null) {
                cancel(CancellationException("Query snapshot error", error))
            }
            offer(snapshot?.toObjects(T::class.java) ?: emptyList())
        }
        awaitClose { registration.remove() }
    }
    a
    l
    • 3
    • 6
  • m

    myungpyo.shim

    11/25/2020, 4:39 AM
    Hi. Can anyone explain me what the difference is between below two functions?
    fun main(): Unit = runBlocking {
        launch {
            //CASE 1 : Will make the application main thread crash
            val result = returnAsKotlinResultFunc()
    
            //CASE 2 : Will not make the application main thread crash
    //        val result = returnAsValueFunc()
    
            println("Return value : $result")
        }.join()
    }
    
    suspend fun returnAsKotlinResultFunc(): Result<String> = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        val result = runCatching {
            delay(100)
            throw IllegalStateException()
        }
        result
    }
    
    
    suspend fun returnAsValueFunc(): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        val result = runCatching {
            delay(100)
            throw IllegalStateException()
        }
        "Result : $result"
    }
    returnAsKotlinResultFunc
    makes the application crash. seems like It can't catch the exception. On the other hand,
    returnAsValueFunc
    can normally handle the exception and return the String result. I think the return type is the only different thing they have. Have I missed something on it? (I am using below compiler options to return Result type.
    kotlinOptions {
        freeCompilerArgs = [
                "-Xallow-result-return-type",
                //"-Xexplicit-api=strict"
        ]
    }
    v
    • 2
    • 4
  • m

    Mark

    11/25/2020, 8:48 AM
    collect()
    vs
    collectLatest()
    : I see the docs for
    collectLatest()
    say: when the original flow emits a new value, action block for previous value is cancelled. But specifically for
    StateFlow
    just about all the examples I see use
    collect()
    . So I’m wondering if the decision whether to use
    collect()
    or
    collectLatest()
    can/should be made on the basis of the nature of the action block (for example, an action block of non-suspending code I suppose the choice is irrelevant - or more generally, is there a problem with cancelling the action block before completion) or whether the nature of
    StateFlow
    also impacts the decision somehow?
    w
    g
    a
    • 4
    • 26
  • a

    aleksey.tomin

    11/25/2020, 3:46 PM
    Ktor CURL client freezes into coroutines on macOS if NSApplication.sharedApplication.run() has started Code freezes into coroutines
    SuspendFunctionGun
    (Code deeper is intrinsic). I thin it’s a coroutines problem: https://youtrack.jetbrains.com/issue/KT-43589
    c
    • 2
    • 11
  • u

    ursus

    11/25/2020, 8:19 PM
    Hi, does Dispatcher.IO release unused threads or are they there forever once lazily initialized?
    l
    • 2
    • 2
  • l

    leandro

    11/25/2020, 8:37 PM
    I thought it would be easy because I will always have an initial value (ZonedDateTime.now()), but if that's too cumbersome I can make its consumers suspend
    w
    e
    u
    • 4
    • 6
  • l

    leandro

    11/25/2020, 8:39 PM
    It feels like it's possible... it would also represent what I actually wanted to represent: emissions of the current time
    b
    • 2
    • 1
  • u

    ursus

    11/25/2020, 11:35 PM
    I have a hard time deciding what methods should be blocking and what should be suspending. Is cancel-ability the rule of the thumb as to make it suspending?
    j
    u
    • 3
    • 3
  • u

    ursus

    11/25/2020, 11:36 PM
    for example this
    private fun generateMac(someUuid: String, base16HexStringKey: String): String {
            val uuidIdBytes = someUuid.toByteArray(UTF_8)
            val keyBytes = base16HexStringKey.toHexByteArray().decodeBase16()
    
            return hmacSha512(uuidIdBytes, keyBytes).encodeBase16().toHexString()
        }
    It just generates hmac of some uuid string ... worth suspending?
    u
    • 2
    • 4
  • k

    Kurt Renzo Acosta

    11/26/2020, 6:55 AM
    Hey everyone. What’s the best way to filter nulls for StateFlow? I have this:
    private val _myFlow = MutableStateFlow<String?>(null)
    val myFlow: Flow<String> get() = _myFlow.filterNotNull()
    But I want to expose the flow as a
    StateFlow
    to the consumer. I can use
    asStateFlow()
    but I can’t use
    filterNotNull()
    anymore as it converts it back to a
    Flow
    m
    • 2
    • 13
  • d

    df

    11/26/2020, 5:01 PM
    Hey there. Not really an issue but I'm trying to understand the behavior of the following flow.
    fun getContent(dropN: Long) = flow {
            val counter = AtomicLong(dropN)
            val resource = javaClass.getResource("/products.csv").toURI()
    
            File(resource).useLines { lines ->
                lines.filter { it.isNotEmpty() }
                    .drop(dropN.toInt())
                    .map { it.toLong() }
                    .chunked(100)
                    .onEach { counter.addAndGet(it.size.toLong()) }
                    .map { getContentByProductIds(it) }
                    .onEach { println("Processed ${counter.get()} lines from input file") }
                    .forEach { emit(it) }
            }
        }
    The flow is collected by multiple co-routines and I see exactly the same lines printed multiple times.
    Processed 100 lines from input file
    Processed 100 lines from input file
    Given the flow definition I would assume the second onEach should only be invoked when the first onEach was invoked before, which should always increment the counter. Why do I still see the same counter value multiple times?
    t
    d
    a
    • 4
    • 10
  • a

    aleksey.tomin

    11/27/2020, 7:23 AM
    How can I investigate a problem “`kotlinx.coroutines.delay(100)` sometimes works 10 seconds”? Some breakpoint?
    b
    s
    u
    • 4
    • 14
  • w

    why

    11/27/2020, 2:57 PM
    Hi.. I have no idea why am I having this error in commonNativeTest
    kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen kotlin.collections.HashMap@dac14b48
    Basically I have a static hashmap to serve caching purposes, since KMP doesn’t have a ConcurrentHashMap -yet, right?- I’m testing using a normal hashmap and reentrantLock() from kotlinx.atomicfu, the hashmap is static - in companion object{} - it always fails in native when you try to put something in it
    l
    • 2
    • 2
  • a

    Ajaydeepak07

    11/28/2020, 1:20 PM
    how mechanism of suspend functions are been paused and resumed in thread and also how coroutines are unblocking the main thread, anyone know please reply.
    h
    t
    u
    • 4
    • 20
  • d

    df

    11/29/2020, 4:56 PM
    What is the correct way to define a method that returns a ReceiveChannel<E>?
    class SomeClass { fun CoroutineScope.producer() = produce { ... } }
    or is it
    class SomeClass { fun producer(scope: CoroutineScrope) = scope.produce { ... } }
    or should (for some reasons) those methods never be methods but just functions? If it's the first one, do I really need to invoke it via
    with(obj) { producer() }
    ? If it's second one, do I just want to pass in
    this
    ? Might sound random but I still find myself frequently in a situation where I know how something can be done but never why.
    z
    • 2
    • 2
  • r

    Roshan P Varghese

    11/29/2020, 4:59 PM
    message has been deleted
    j
    • 2
    • 4
  • k

    kelvinharron

    11/30/2020, 11:22 AM
    Hi folks, can I ask if using coroutines with
    native-mt
    makes a difference when used in a standard kotlin android project? We see
    native-mt
    bumps occasionally like (kotlinCoroutinesVersion from 1.4.1 to 1.4.2-native-mt) and as I understand it,
    native-mt
    enables multithreaded coroutine support on Kotlin native projects only. One to ignore in our use case? Thanks in advance.
    n
    • 2
    • 2
  • b

    bbaldino

    11/30/2020, 5:41 PM
    I've got a use case that I thought would be a good fit for structured concurrency, but I'm struggling with it and not sure if I'm missing something or trying to force a square peg into a round hole. I've got basically a class/job hiearchy, but need the following behavior: 1. If any sub-task errors, then the parent should know so it can cancel the others (this works well with structured concurrency) 2. If any sub-task finishes, then the parent should know so it can stop all the others (This has been one of the trickier parts to get working with structured concurrency) 3. Stopping the parent should stop all the children (this works well with structured concurrency) 4. Tasks need to perform non-trivial cleanup upon completion, both in the 'clean' finish and error modes, but I want to be able to do this on a class level, not just a 'task' level. That is: a class may launch several child jobs, but I don't want to run the cleanup on the completion of each of those child jobs, more on the class' "scope" level. (I even played with writing a
    CoroutingScope#onFinish
    helper which delayed wrapped an indefinite delay in a try/finally and called a cleanup method in the
    finally
    block, but it feels wrong). Of these, I think #2 is the biggest sticking point: I find myself wishing I could create a child coroutine scope but wait for any child to finish, instead of all children to finish (like
    coroutineScope
    and
    runBlocking
    do). Does that exist?
    l
    m
    • 3
    • 19
  • a

    allan.conda

    11/30/2020, 5:46 PM
    What’s the safest way to apply a reduce function to a MutableStateFlow?
    w
    • 2
    • 22
  • b

    Byron Katz

    11/30/2020, 6:43 PM
    Question for the coroutine experts here: If I have a program that doesn't really do much blocking - like let's say, a single run of the program just does a bunch of math and local data collection transformations, and I run that program again and again as fast as possible, would there be much call for coroutines? I am thinking not - rather, that just having a fixed set of threads (1 per core) should be as effective. I'm thinking that coroutines really shine when there's significant blocking, is that correct?
    t
    • 2
    • 22
  • b

    bbaldino

    11/30/2020, 10:02 PM
    I'm observing something that I'm trying to nail down, but wondering if maybe it isn't a guarantee: I launch a couple tasks via
    val task = myScope.async { ... }
    , and then I wait on those deferreds in a
    select
    block. When a task throws, most of the time the exception I catch (around my select) is the actual exception thrown by the task. But sometimes it's a
    JobCancellationException
    with the cause being the actual exception. Is that expected? Or is there something weird going on there?
    k
    • 2
    • 5
  • f

    Florian

    12/01/2020, 6:58 AM
    Is
    invokeOnCompletion
    a good place to hide a progress bar if a Coroutine was either finished or cancelled?
    .invokeOnCompletion {
        _loading.postValue(false)
    }
    👍 1
    a
    t
    • 3
    • 15
  • u

    ubu

    12/01/2020, 1:45 PM
    Hello there! A quick question here. When inside some method inside a ViewModel I launch two coroutines:
    fun someFun() {
       val job1 = viewModelScope.launch { operation1() }
       val job2 = viewModelScope.launch { operation2() } 
    }
    Are these two operations sequential by default? Operation in the first launch block is completed, and only then, the second operation is started.
    🇳🇴 3
    j
    r
    +3
    • 6
    • 7
  • k

    Kevin M Granger

    12/01/2020, 5:47 PM
    Is there a way to create a
    suspend fun
    out of a home-grown coroutine? Suppose I have some computation-heavy code that has some natural "pause" points. I'd like to use existing coroutine tools to handle cancellation and timeouts-- but everything expects you to use a
    suspend
    function. In other words, I more or less have this:
    sealed class ComputationResult {
      abstract fun finish(): Int
      class Finished(val result: Int) : ComputationResult() {
        overide fun finish() = result
      }
      class InProgress(val rest: Computation) : ComputationResult() {
        override fun finish() = rest().finish()
      }
    }
    
    // does not currently implement Continuation<Unit> but could easily do so
    class Computation {
      operator fun invoke(): ComputationResult {
        TODO()
        // implementation elided here, but it could easily check
        // to see if it was cancelled
      }
    }
    Can I turn it into
    suspend fun compute() -> Int
    ?
    z
    • 2
    • 3
  • b

    bbaldino

    12/01/2020, 6:33 PM
    If I do:
    val t = scope.async { ... }
    val u = scope.async { ... }
    try {
        select<Unit> {
            t.onAwait { ... }
            u.onAwait { ... }
        }
    } catch (c: CancellationException) {
        ...
    } catch (t: Throwable) {
       ...
    }
    where
    scope
    is not cancelled anywhere and one of the
    t
    ,
    u
    tasks throws an exception, should I always be able to catch the exception that was thrown in my block? I'm seeing that most of the time I get the exception thrown by
    t
    or
    u
    , but sometimes I get a
    CancellationException
    wrapping the exception thrown by
    t
    or
    u
    and I'm trying to figure out if this is to be expected when using
    select
    or if I'm doing something wrong.
    b
    • 2
    • 27
  • s

    spierce7

    12/02/2020, 4:13 AM
    If I have a
    List<Flow<String>>
    and I want to merge them all into a single
    Flow<String>
    , what’s the best way to do that?
    c
    z
    • 3
    • 6
  • s

    spierce7

    12/02/2020, 4:24 AM
    If I have access to a
    CoroutineContext
    via
    coroutineContext
    , what is the best way for me to create child coroutines? I’m assuming I need to create a
    CoroutineScope
    , but there aren’t any utility methods I’ve found for this, making me think that there might be a better way?
    z
    b
    • 3
    • 4
Powered by Linen
Title
s

spierce7

12/02/2020, 4:24 AM
If I have access to a
CoroutineContext
via
coroutineContext
, what is the best way for me to create child coroutines? I’m assuming I need to create a
CoroutineScope
, but there aren’t any utility methods I’ve found for this, making me think that there might be a better way?
z

Zach Klippenstein (he/him) [MOD]

12/02/2020, 4:48 AM
To use structured concurrency, use
coroutineScope {}
. Otherwise, you can use
CoroutineScope(coroutineContext)
s

spierce7

12/02/2020, 4:57 AM
I looked at the source for
coroutineScope {}
. It doesn’t look like it uses the current scope. If I call
coroutineScope {}
inside a coroutine, will it create child coroutines?
b

bezrukov

12/02/2020, 6:31 AM
Yep it takes your current context and creates child scope. coroutineScope {} suspends until all children completes
z

Zach Klippenstein (he/him) [MOD]

12/02/2020, 5:21 PM
Yes it does, that’s pretty much its main use case.
View count: 3