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

    Rick

    11/26/2019, 7:01 AM
    hi! i am new to kotlin's coroutines. i am confused now when a coroutine will suspend. manually call delay() wiil help but it seem to be too low level. can dispatcher know when a coroutine is blocking and suspend it itself
    o
    • 2
    • 12
  • h

    hikkidev

    11/26/2019, 7:16 AM
    Hi there 😺. How can I make PublishRelay through Kotlin Cold Flows ? I know about ConflatedBroadcastChannel, but it hot channels.
    p
    g
    • 3
    • 3
  • t

    tseisel

    11/26/2019, 9:56 AM
    Hi ! I have a design problem with
    Flow
    . I have a source flow the emits the current result of a request in database whenever it changes (like a
    Flow
    returned by Android Room). I decided to expose the result of those request with a repository.
    interface DataSource {
        val flow: Flow<List<Foo>>
    }
    
    class Repository(
        private val source: DataSource
    )
        val diff: Flow<Diff<Foo>> get() = TODO()
        suspend fun getLatest(): List<Foo> = TODO()
    }
    How can I transform the source flow to adapt it to the needs of the
    Repository
    ? (The
    Diff
    is calculated from the latest and the previous list of `Foo`s.) Is it possible to cache the latest value just like Android
    LiveData
    , to avoid costly database queries when repeateadly reading the latest values ?
    o
    g
    • 3
    • 7
  • d

    dave08

    11/26/2019, 1:23 PM
    Will this (on Android) print Finished before Hi, or Hi before finished... it seems like repl and scratch files don't work for this
    val dispatcher = Dispatchers.Main.immediate
    val scope = CoroutineScope(dispatcher)
    
    fun main() {
        println("Started.")
    
        scope.launch { delay(30); println("Hi!") }
    
        println("Finished.")
    }
    g
    • 2
    • 4
  • d

    dave08

    11/26/2019, 1:29 PM
    I'm not sure how immediate works, doesn't it run on the caller's thread and Hi would be printed before Finished... (maybe I have to add a
    yield()
    )?
    g
    • 2
    • 24
  • r

    Robert Jaros

    11/26/2019, 2:03 PM
    is
    1.3.2-1.3.60
    the official release of coroutines for kotlin 1.3.60 ?
    ➕ 3
    s
    e
    • 3
    • 2
  • d

    deviant

    11/26/2019, 2:54 PM
    is it possible to solve exactly this issue with coroutines in elegant way? https://stackoverflow.com/questions/12450402/java-synchronizing-based-on-a-parameter-named-mutex-lock
    a
    • 2
    • 1
  • t

    tseisel

    11/27/2019, 1:09 PM
    Since
    ReceiveChannel<T>.onReceiveOrNull
    has been deprecated, it is suggested to replace it with the
    onReceiveOrNull
    extension function. But I find that it's surprisingly hard to use that function: 1. Since there is a member property
    onReceiveOrNull
    it takes precedence over the extension. 2. Since
    onReceiveOrNull
    is a function, the block passed as select clause is incorrectly interpreted as an extra lambda parameter. While the following workaround code works:
    import kotlinx.coroutines.channels.onReceiveOrNull as onReceiveOrNullExt
    
    select {
        channel.onReceiveOrNullExt().invoke { foo ->
            [...]
        }
    
        anotherChannel.onReceive { bar ->
            [...]
        }
    }
    It is not as convenient as the original Select API. Wouldn't it be better to convert that extension function to an extension property with a different name ?
    e
    • 2
    • 1
  • j

    jimn

    11/27/2019, 7:55 PM
    how do i partition a sequential flow into predetermined buckets of flows without triggering the collection?
    o
    s
    • 3
    • 21
  • s

    spand

    11/28/2019, 9:31 AM
    Question about adapting callback to suspend api. I have the following code below adapting javascript
    FileReader
    to suspend. Does this look good? • Should I cancel the continuation when the underlying resource is aborted (ie. by the browser) ? • Is this sequence safe ?
    continuation.invokeOnCancellation -> abort() -> onabort -> continuation.cancel()
    suspend fun Blob.readAsDataUrl2(): String {
        val fileReader = FileReader()
        return suspendCancellableCoroutine { continuation ->
            fileReader.onload = {
                val dataUrl = fileReader.result as String
                continuation.resume(dataUrl)
            }
            fileReader.onerror = {
                continuation.resumeWithException(DomExceptionThrowable(fileReader.error as DOMException))
            }
            fileReader.onabort = {
                continuation.cancel()
            }
            continuation.invokeOnCancellation { fileReader.abort() }
    
            fileReader.readAsDataURL(this) // <-- Async work starts here
        }
    }
    e
    • 2
    • 4
  • b

    bnn

    11/29/2019, 4:03 AM
    I’m wondering wether it’s good to use runCatching inside suspend function. It’s something like below.
    suspend fun foo(): Foo {
        return runCatching {
            // do something with calling other suspend functions
            Foo()
        }.getOrElse { exception ->
            // do somethiing
            Foo()
        }
    }
    The code example above will not propagate CancellationException to caller. Is it OK? Or would I better to consider propagate CancellationException, like
    suspend fun foo(): Foo {
        return runCatching {
            // do something with calling other suspend functions
            Foo()
        }.getOrElse { exception ->
            if (exception is CancellationException) {
                throw exception
            }
            // do something
            Foo()
        }
    }
    In my opinion, suspend functions are better to propagate CancellationException. But, when we use runCatching inside it, there might be kind of boilerplate like above. Are there idiomatic ways to handle coroutines cancellation with runCatching. Or should I avoid to use it inside suspend function?
    p
    • 2
    • 1
  • j

    Jordi Saumell

    11/29/2019, 8:30 AM
    Hello! I have a question about channels/flow: I’d like to emit events and be able to cancel subscription and later have another instance subscribe to the same channel (with the events accumulated when there is no subscriber). My understanding is that this can be achieved with a Channel with unlimited capacity, but the problem I face is that when the subscriber’s scope is cancelled the channel is closed. If I use GlobalScope it does not occur, but then it is my understanding that it is not unsubscribing. So, how can I have a channel that does not get closed when I unsubscribe?
    o
    • 2
    • 2
  • p

    Paul Woitaschek

    11/29/2019, 12:38 PM
    All right, I need help. After updating my application I faced a lot of crashes on android 7 devices. I couldn't reproduce it on my nexus or on the emulator so I bought one of the crashing devices. After spending half of the day I finally managed to find the root cause and I can reproduce it in a hello world project.
    class MainActivity : Activity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            CoroutineScope(SupervisorJob() + Dispatchers.Main).launch {
                while (true) {
                    combine(flowOf(Unit), flowOf(Unit)) { _ -> Unit }.collect()
                }
            }
        }
    }
    This leads to a sigsegv
    Flags: 0x28c8bf46
        Package: com.example.weirdcrash v1 (1.0)
        Foreground: Yes
        Build: TCL/5009D/U5A_PLUS_3G:7.0/NRD90M/5009D_ALWE_V2.9_20180529:user/release-keys
        
        *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        Build fingerprint: 'TCL/5009D/U5A_PLUS_3G:7.0/NRD90M/5009D_ALWE_V2.9_20180529:user/release-keys'
        Revision: '0'
        ABI: 'arm'
        pid: 29639, tid: 29639, name: mple.weirdcrash  >>> com.example.weirdcrash <<<
        signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x15608
            r0 00015000  r1 12d35700  r2 00000002  r3 00000000
            r4 af58a6d8  r5 12d31ee0  r6 12d37280  r7 00000000
            r8 12d35700  r9 ac684400  sl 12cb0a90  fp 12d33bf8
            ip bef2f84c  sp bef2f8b0  lr 9901f5ef  pc 9901f608  cpsr 000f0030
        
        backtrace:
            #00 pc 00000608  /dev/ashmem/dalvik-jit-code-cache (deleted)
            #01 pc 000005ed  /dev/ashmem/dalvik-jit-code-cache (deleted)
         29639
    I currently see about 1200 affected users; is there anythign I can do here?
    😱 6
    e
    a
    t
    • 4
    • 9
  • c

    Colton Idle

    11/29/2019, 10:25 PM
    I'm writing my first coroutine in a production app! It's an Android app that is using Retrofit with coroutines.
    viewModelScope.launch {
                    val userProfileResponse = apiManager.client!!.getProfile()
                    if (userProfileResponse.isSuccessful) {
                        _viewState.value = _viewState.value?.copy(isLoading = false, profile = userProfileResponse.body())
                    } else {
                        Log.e(TAG, "Not success")
                    }
            }
    and it works! BUT I tried to run the app in airplane mode and it crashes. If I use a try catch it won't crash, but I'm confused by why the IDE doesn't force me to have a try/catch. Does anyone know why?
    o
    g
    • 3
    • 23
  • w

    william

    12/01/2019, 4:04 AM
    is there something with coroutines that is analogous to Subjects from RxJava?
    v
    • 2
    • 1
  • a

    Alexjok

    12/01/2019, 9:14 AM
    Hello, do we have something like coroutines job executor? Or meby someone already write thing like that? Idea is have queue or another structure of coroutine jobs and execute them at concrete time, in other words - coroutines scheduler
    o
    d
    • 3
    • 4
  • o

    orafaaraujo

    12/02/2019, 10:29 AM
    Hello everyone, Is it possible to hear a
    BroadcastChannel
    out of a
    Coroutine
    ?
    p
    • 2
    • 11
  • d

    Dominaezzz

    12/02/2019, 3:53 PM
    So I want to traverse a read only (or frozen if you will) tree concurrently with coroutines.
    sealed class Tree {
        data class Parent(val children: List<Tree>): Tree()
        data class Leaf(val value: Int): Tree()
    }
    
    fun Tree.simpleSum(): Int {
        return when (this) {
            is Tree.Parent -> children.map { it.simpleSum() }.sum()
            is Tree.Leaf -> value
        }
    }
    
    fun Tree.concurrentSum(): Int {
        return when (this) {
            is Tree.Parent -> runBlocking {
                children.map { async { it.simpleSum() } }
                    .awaitAll().sum()
            }
            is Tree.Leaf -> value
        }
    }
    
    suspend fun Tree.questionableSum(): Int {
        return when (this) {
            is Tree.Parent -> coroutineScope {
                children.map { async { it.questionableSum() } }
                    .awaitAll().sum()
            }
            is Tree.Leaf -> value
        }
    }
    I basically want to sum up all the nodes in the tree. Right now I create a
    Job
    for every immediate child of the root (
    concurrentSum
    ), but I might not be using all the parallelism available. I'm tempted to recursively create a
    Job
    at every node (
    questionableSum
    ) which would use all the parallelism but I get the feeling that that's not the way to go. Is there a "right" way to go about this?
    ➕ 1
    b
    • 2
    • 3
  • j

    Jordi Saumell

    12/02/2019, 4:20 PM
    I’m quite new to flows and channels and I have a question: what is the benefit of consuming a channel as a flow? My understanding from reading Roman Elizarov is that flows are cold and channels hot, so if the emitter is a channel (hot), listening to it from a flow could not make it cold (correct me if I’m wrong). Therefore, what is it used for?
    s
    s
    j
    • 4
    • 7
  • o

    orafaaraujo

    12/03/2019, 10:24 AM
    Is
    Flow
    still experimental on
    1.3.2
    ? Tha changelog says that is not but my AS keep me asking to put
    @ExperimentalCoroutinesApi
    l
    i
    +2
    • 5
    • 6
  • r

    Ruckus

    12/03/2019, 4:59 PM
    Can you not do any exception handling in coroutines? I have this:
    launch { field.setAs { calculate() } }
    ...
    private fun StringProperty.setAs(calc: () -> Any) = set(
        try {
            calc().toString()
        } catch (e: Exception) {
            e.message
        }
    )
    (Note that
    setAs
    has no suspension at all)
    But if
    calc
    throws an exception, it isn't caught and instead just crashes. Am I missing something obvious?
    s
    • 2
    • 2
  • l

    Luke Rohde

    12/03/2019, 6:25 PM
    is there anything wrong with doing cleanup like this in a flow builder block?
    flow {
      for (i in collection) {
        try {
          emit(i)
        } finally {
          doCleanupOn(i)
        }
      }
    }
    is there a better way to accomplish this?
    o
    r
    +3
    • 6
    • 35
  • i

    itnoles

    12/03/2019, 8:04 PM
    It is quite interesting for a method to throw IOException end up to be incorrect blocking method calls.
    z
    • 2
    • 2
  • i

    Ive Vasiljevic

    12/04/2019, 1:22 PM
    fun main() = runBlocking {
        val job = launch {
            println("Coroutine start")
            launch {
                println("Child coroutine start")        
                println("Child coroutine end")
    
                launch {
    
                    println("Child-inner coroutine start")        
                    println("Child-inner coroutine end")
                }
            }
            println("Coroutine end")
            println("Coroutine end!")
        }
        println("Join")
        println("Done")
    }
    Why is Join and Done executed before job? And when calling job.join() between println("Join") and println("Done") job is executed at the place of calling job.join()?
    d
    l
    +6
    • 9
    • 16
  • g

    Gabriel Machado

    12/04/2019, 1:35 PM
    Is the return type of
    suspend
    functions always
    Object
    when compiled?
    :yes: 3
    d
    • 2
    • 2
  • t

    Tucker Barbour

    12/04/2019, 3:44 PM
    Is there a recommended pattern for multiple producers and single consume? For example:
    runBlocking {
      val channel = Channel<Int>(bufferSize)
      val producers = (0..producerCount).map { launch { produceValues(channel) } }
    
      while (producers.any { it.isActive }) {
        // time-of-check time-of-use race condition here. If there were any producers active at the time of check but had finished sending messages, we end up waiting on messages that we'll never receive
        val message = channel.receive()
        doSomethingWithMessage(message)
      }
    
      coroutineContext.cancelChildren()
    }
    If I were using Java I would probably use a CountdownLatch to coordinate the completion of the Producers with the Consumers. Is there a similar pattern for coroutines?
    a
    • 2
    • 8
  • a

    ApplePeel

    12/05/2019, 10:42 AM
    how can i user this in macos and windows....
    ❓ 4
    a
    • 2
    • 1
  • v

    Vsevolod Ganin

    12/05/2019, 11:06 AM
    [v1.3.2] Can anybody explain why
    CoroutineExceptionHandler
    installed in top-most
    runBlocking
    is not being called? I read all docs but can’t quite grasp the sense of it. Example:
    fun main(): Unit = runBlocking(CoroutineExceptionHandler { _, e ->
        println("Boom: $e")
    }) {
        (0..10).map {
            launch {
                println("Throw in attempt #$it")
                throw RuntimeException("Attempt #$it")
            }
        }
        Unit
    }
    s
    a
    • 3
    • 25
  • j

    jimn

    12/05/2019, 4:39 PM
    how does one do flow1.collect and flow2.collect in unison to combine right and left halves?
    d
    a
    • 3
    • 12
  • v

    v0ldem0rt

    12/05/2019, 9:33 PM
    So I am a deep down in stack where I am writing something like TurboFilter for Logback. At this point I can't write suspend functions. How can I access something from coroutineScope.
    o
    • 2
    • 2
Powered by Linen
Title
v

v0ldem0rt

12/05/2019, 9:33 PM
So I am a deep down in stack where I am writing something like TurboFilter for Logback. At this point I can't write suspend functions. How can I access something from coroutineScope.
o

octylFractal

12/05/2019, 9:34 PM
depending on if it needs to be blocking or async. blocking use
runBlocking
, async just use a CoroutineScope object (create one and make sure it has the correct lifecycle for whatever you're doing)
v

v0ldem0rt

12/05/2019, 9:40 PM
I don't wanna do runBlocking since it's a filter and function needs to be highly performant
View count: 3