https://kotlinlang.org logo
Docs
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
  • i

    Icaro Temponi

    07/30/2019, 7:27 PM
    and if the awaitClose lambda would be called properly in this case
    d
    • 2
    • 3
  • k

    Kulwinder Singh

    07/31/2019, 6:51 AM
    Hi, i want to schedule coroutine for every 5-9 minutes in my app, my actual requirement is to show ad after 5-9 minute so that's why i want to use coroutine to
    delay
    execution for random time between 5-9 mins, So what is best way to do it with kotlin in android ? Simply using
    delay
    or
    flows/channels
    ?
    g
    t
    +3
    • 6
    • 21
  • a

    adeln

    07/31/2019, 7:50 AM
    hey folks! I have a list of parallel computations. How would I write a function like this? Can’t really wrap my head around it
    fun <T> List<Deferred<T>>.toFlow(): Flow<T>
    I want the flow to emit values as soon as they become available
    u
    m
    g
    • 4
    • 41
  • a

    adeln

    07/31/2019, 9:25 AM
    it’s so weird that
    callbackFlow
    just calls
    channelFlow
    🙂
    g
    • 2
    • 7
  • p

    Paul N

    07/31/2019, 11:20 AM
    I have the following use case: I fire off a number of REST calls to a very slow REST service, and want to return a filtered list of the results. So currently I'm creating a channel, launching each REST call in a coroutine, and writing the result of each to a channel. I then iterate through the channel, do a manual filter via an if statement, and add any filtered result to a mutable list. This feels a bit imperative to me - is there a better way of doing this that doesn't for example, rely on a mutable list and manual filtering ? Should I be using Flow and filters instead ?
    val output = mutableListOf<String>()
                for (something in channel) {
                    if (some condition based on something) {
                        output.add(something)
                    }
    
                }
    d
    a
    • 3
    • 9
  • u

    ursus

    07/31/2019, 3:09 PM
    anyways, given I wrapped the executor with IO.. that was kind of my rationale, thread spawn + switch from IO to IO seems pointless and wasteful, I liked that it didnt apply threads
    g
    • 2
    • 5
  • i

    Icaro Temponi

    07/31/2019, 5:49 PM
    Just to make shure I got that right, I'd like to know if this chain does the following: - Run updateNotifications on each emission - If the function takes too long to execute, buffer 1 emission and ignore all others - When the function finishes, run it again if there's a buffered emission
    flow()
            .conflate()
            .buffer(1)
            .onEach { updateNotifications() }
            .launchIn(GlobalScope)
    l
    z
    d
    • 4
    • 6
  • l

    Lorenzo Testa

    08/01/2019, 11:34 AM
    Hi, if I have two existing scopes and want to launch a coroutine that cancel if any of the two scopes is cancelled, how can I do it?
    i
    • 2
    • 4
  • h

    halim

    08/01/2019, 2:34 PM
    hi
    runBlocking {
          println("start main")
          execute(coroutineContext) {  println("some long operation")  }
          println("main done")
    }
    
    fun execute(context: CorouitneContext, action: suspend () -> Unit) {
          action.startCorouitne(Continuation(context + <http://Dispatchers.IO|Dispatchers.IO>) {
                println("corouitne complete")
         })
    }
    so when execute : start main main done, i expected to see : corouitne complete "startCorouitne" start a new coroutine in my case i bound it to runBlocking scope (with context as parent) and with dispather IO, so i expect to see "coroutine complete" in console ?? i think this new coroutne created by startCoroutine its not bound to runBlocking so when main is finish its ignore this corouitne
    l
    • 2
    • 1
  • z

    zak.taccardi

    08/01/2019, 3:50 PM
    Does
    Flow<T>
    support multicasting yet?
    d
    r
    g
    • 4
    • 7
  • a

    Aslam Hossin

    08/01/2019, 4:20 PM
    How can I manage Error in coroutines in case of API requesting? Using RxJava, we can easily manage error in onError operator. I want to know is there any operator like RxJava
    z
    m
    +6
    • 9
    • 29
  • g

    groostav

    08/01/2019, 7:31 PM
    This lambda with receiver stuff in the kotlinx coroutines API is playing with fire.
    d
    b
    • 3
    • 18
  • l

    Luis Munoz

    08/01/2019, 8:25 PM
    Is this code thread safe? If update() is called from different threads it will use the context of Example: CoroutineScope so it will never be inside update() from two different threads correct?
    Untitled
    g
    d
    • 3
    • 36
  • m

    Marko Mitic

    08/01/2019, 9:17 PM
    ^ this inspired me to test whether switching threads in a coroutine flushes the cache similarly to java
    synchonized
    block. Here's the test, results in thread
    import kotlinx.coroutines.*
    import kotlinx.coroutines.Dispatchers
    import kotlinx.coroutines.launch
    import kotlinx.coroutines.yield
    
    class Test {
        var i = 0
    
        suspend fun countWithThreadSwitching(){
            repeat(10) {
                i++
                delay(1) //yield() didn't make coroutine resume on another thread
            }
            println(i)
        }
    }
    
    fun main() = runBlocking {
        coroutineScope{
            repeat(100) {
                launch(Dispatchers.Default) {
                    Test().countWithThreadSwitching()
                }
            }    
        }
    }
    d
    d
    j
    • 4
    • 27
  • a

    ansman

    08/02/2019, 1:06 PM
    I wish there was a shorthand/more optimized version of this:
    someFlow
      .conflate()
      .broadcastIn(someScope)
      .asFlow()
    g
    • 2
    • 1
  • a

    Aldo Wachyudi

    08/03/2019, 2:49 AM
    So far, I understand the basic about coroutine topic (CoroutineBuilder, CoroutineScope, Dispatchers. etc.). However, I find one topic in coroutine that is difficult for me to understand. It’s about the cancellation of coroutine(s). I wrote the detailed question on StackOverflow here: https://stackoverflow.com/questions/57335077/how-to-properly-handle-cancellation-in-coroutines-computation-code If you guys have time, please help me to answer the question. I will re-post the question on reply thread.
    k
    s
    • 3
    • 19
  • y

    yschimke

    08/03/2019, 10:02 AM
    Is there an established pattern for memoizing async tasks? within some coroutine scope? if the scope is per request, it would be great to avoid duplicate work etc
    l
    g
    • 3
    • 6
  • c

    Chainchelliah

    08/03/2019, 7:17 PM
    Room suspend function with Livedata not working. Conversion error is occurred while compiling. Room version is 2.1.0. PS: I resolved this error by removing the suspend keyword. Any other ways to resolve this error.
    m
    • 2
    • 1
  • t

    thana

    08/04/2019, 11:22 AM
    i just stumbled across this sentence in the
    coroutineContext
    documentation "By convention, should contain an instance of a job to enforce structured concurrency.". What does it mean? It'spossible that a context does NOT contain a job? what are the consequences if a job instance is missing?
    d
    m
    +2
    • 5
    • 67
  • b

    bombe

    08/04/2019, 4:14 PM
    I have a problem wrapping my head around coroutines and wrapping coroutines around an existing callback-based API: https://gist.github.com/Bombe/fb1ec487ea03614d96e9d152f21e64cc – the exception from line 55 is being thrown from line 55 and not from line 57, like I’d expect. What’s going on there?
    z
    • 2
    • 14
  • a

    Aldo Wachyudi

    08/05/2019, 2:39 AM
    Today I found there are two functions in coroutine package;
    coroutineScope
    or
    supervisorScope
    . When should we use it instead of using
    CoroutineScope(SupervisorJob())
    ? How do we cancel
    coroutineScope
    or
    supervisorScope
    ?
    g
    z
    • 3
    • 4
  • l

    Lorenzo Testa

    08/05/2019, 10:42 AM
    I don't understand why this code throws
    ClosedSendChannelException: Channel was closed
    , can someone explain it to me?
    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    
    @UseExperimental(ExperimentalCoroutinesApi::class)
    fun main() = runBlocking {
        val scope = CoroutineScope(Job())
        val f = channelFlow {
            launch(scope.coroutineContext) {
                repeat(10) {
                    delay(200L)
                    send(it)
                }
            }
        }
        f.collect {
            println(it)
        }
        delay(3000L)
    }
    m
    g
    a
    • 4
    • 32
  • e

    Eric Martori

    08/05/2019, 1:17 PM
    I have the following setup:
    val flow get() = channel.asFlow()
        private val channel =
            BroadcastChannel<T>(???)
    I want that each time a user of the API calls
    flow.collect{}
    the last value is received on collect, but no values are lost if they are received in quick succession and the sender should suspend if needed for this to happen. With
    CONFLATED
    I get the last value emited on each new
    collect
    and with
    BUFFERED
    I get the "suspend if needed, don't loose any values" behaviour. Is there a way to achieve what I want?
    z
    • 2
    • 4
  • v

    v0ldem0rt

    08/05/2019, 1:18 PM
    I can't seem to get
    suspend operator fun <T> invoke(block: suspend () -> T): T {
            // ...
        }
    to work. Does
    invoke
    work with
    suspend
    keyword?
    e
    w
    +2
    • 5
    • 8
  • a

    aerb

    08/05/2019, 5:29 PM
    Is there a less
    try
    /
    catch
    oriented way of accessing the result of
    async
    ? Thinking of something similar to
    Result
    m
    z
    l
    • 4
    • 11
  • r

    rook

    08/05/2019, 9:29 PM
    I’m trying to coerce Realm to work with coroutines, but my
    ReceiveChannel
    is coming back already closed from this signature
    @ExperimentalCoroutinesApi
    override fun CoroutineScope.messageUpdateProducer(): ReceiveChannel<List<Message>> = produce {
        realm.where(RealmMessage::class.java).findAll().addChangeListener { results ->
            offer(results.takeIf { it.isNotEmpty() }?.map { it.messageActual } ?: listOf())
        }
    }
    It looks like, from the documentation that if the producer encounters an error, it will close automatically, but I’m not sure what’s generating an error in there. I’m handling all the null cases and my crashes are only generating a stack trace internal to the channel mechanism.
    kotlinx.coroutines.channels.ClosedReceiveChannelException: Channel was closed
            at kotlinx.coroutines.channels.Closed.getReceiveException(AbstractChannel.kt:1094)
            at kotlinx.coroutines.channels.AbstractChannel$ReceiveSelect.resumeReceiveClosed(AbstractChannel.kt:993)
            at kotlinx.coroutines.channels.AbstractSendChannel.helpClose(AbstractChannel.kt:332)
            at kotlinx.coroutines.channels.AbstractSendChannel.close(AbstractChannel.kt:271)
            at kotlinx.coroutines.channels.SendChannel$DefaultImpls.close$default(Channel.kt:95)
            at kotlinx.coroutines.channels.ProducerCoroutine.onCompleted(Produce.kt:98)
            at kotlinx.coroutines.channels.ProducerCoroutine.onCompleted(Produce.kt:91)
            at kotlinx.coroutines.AbstractCoroutine.onCompletionInternal(AbstractCoroutine.kt:102)
            at kotlinx.coroutines.JobSupport.tryFinalizeSimpleState(JobSupport.kt:274)
            at kotlinx.coroutines.JobSupport.tryMakeCompleting(JobSupport.kt:784)
            at kotlinx.coroutines.JobSupport.makeCompletingOnce$kotlinx_coroutines_core(JobSupport.kt:764)
            at kotlinx.coroutines.AbstractCoroutine.resumeWith(AbstractCoroutine.kt:111)
            at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:46)
            at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5223)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
    z
    d
    +2
    • 5
    • 10
  • a

    ahulyk

    08/06/2019, 10:16 AM
    Retrofit does not support Flow. So if I need to merge concurrent requests using 'flatMapMerge' what is the right way to do this?
    d
    l
    d
    • 4
    • 9
  • d

    Dominaezzz

    08/06/2019, 10:26 AM
    I have a use case for
    BroadcastChannel
    but I'm not sure how to expose it. Should I literally expose the
    BroadcastChannel
    for users to call
    openSubscription()
    or should I wrap this up?
    z
    • 2
    • 2
  • b

    Big Chungus

    08/06/2019, 10:52 AM
    Is there a way to forcefully terminate a coroutine?
    g
    d
    n
    • 4
    • 13
  • m

    Manuel Vivo

    08/06/2019, 2:28 PM
    Do Flow and Channels have any size restrictions? What happens if you send a 1MB object?
    j
    • 2
    • 2
Powered by Linen
Title
m

Manuel Vivo

08/06/2019, 2:28 PM
Do Flow and Channels have any size restrictions? What happens if you send a 1MB object?
j

jw

08/06/2019, 2:30 PM
On JVM/Android they're passed by reference so every object only requires 32 or 64 bits no matter what size it is
m

Manuel Vivo

08/06/2019, 2:32 PM
👌 thanks!
View count: 1