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

    Slackbot

    08/29/2018, 4:28 PM
    This message was deleted.
    l
    • 2
    • 1
  • s

    Seri

    08/29/2018, 5:24 PM
    How would you all expose state stored inside of an Actor? Ideally, I’d be able to observe changes to variables inside the Actor from other classes. I’ve got this implemented already in Android using LiveData, but it’s a bit hacky
    g
    w
    • 3
    • 7
  • a

    aaverin

    08/29/2018, 6:54 PM
    Anybody else having issues with debug breakpoints inside coroutines?
    s
    • 2
    • 1
  • a

    aaverin

    08/29/2018, 7:33 PM
    Is there some kind of
    blockingProduce
    ? I have an async callback that I want to wrap into a channel
    d
    d
    • 3
    • 17
  • b

    bdawg.io

    08/30/2018, 2:50 AM
    It looks like kotlinx-coroutines-io is missing the 0.25.0 release. I checked the kotlin bintray and maven central
    c
    • 2
    • 1
  • s

    svenjacobs

    08/30/2018, 1:33 PM
    Hi all, what's the best approach for a long-running coroutine with multiple "receivers" ... let's say I have a coroutine which calculates some complex value or fetches something via network. I have multiple locations that might call this coroutine. But instead of starting this coroutine n times it should only run once an deliver the value to all receivers. Is a ConflatedBroadcastChannel here the best architectural choice? So putting the value into the channel so that everyone can take it when needed?
    v
    b
    • 3
    • 3
  • o

    otakusenpai

    08/30/2018, 2:33 PM
    Hello guys, My program calls a function inside a coroutine, which calls a plugin. Now this plugin requires to wait for a specified period of time. I tried java.util.Timer and it didnt work(i put 60 secs but even after that it didnt work). Now i think i'll try this https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.concurrent/java.util.-timer/schedule.html . But what Im unsure about is that if a plugin can have a coroutine call inside it(also, im not sure if Schedule is a coroutine thingy). Thanks.
    m
    g
    • 3
    • 47
  • a

    aaverin

    08/30/2018, 7:01 PM
    How to keep an active subscription to the channel? Documentation doesn’t mention BroadcastChannel/ConflatedBroadcastChannel and I need to keep active subscription to one of those
    s
    l
    • 3
    • 24
  • o

    oday

    08/30/2018, 7:05 PM
    by the time that this code reaches the oncomplete listener, requests to an API which use the
    carsService
    object have already went out
    d
    • 2
    • 39
  • r

    rocketraman

    08/30/2018, 9:05 PM
    I have a generic
    retry
    function that takes an
    action
    lambda. Is there a way for me to define this function in such a way that the
    action
    lambda can be either suspending or non-suspending depending on the caller?
    l
    e
    • 3
    • 5
  • i

    IRomanov

    08/30/2018, 9:49 PM
    Hello. I want to use
    async
    coroutine builder to execute some blocking code in parallel. I use my custom thread pool for that. But is it ok to call regular (non-suspending) function inside
    async
    ?
    fun doSomething(s: String): String {
    // blocking code
    }
    
    val def1 = async(myContext) { doSomething("a") }
    val def2 = async(myContext) { doSomething("b") }
    // ...
    
    println("${def1.await()} ${def2.await()}")
    r
    u
    • 3
    • 6
  • a

    Albert

    08/31/2018, 8:03 AM
    When you have something like this:
    val dispatcher = Executors.newFixedThreadPool(64).asCoroutineDispatcher()
    
    runBlocking(dispatcher) {
        launch {
            // do something
        }
    }
    I thought
    launch
    in the example would automatically inherit the
    dispatcher
    , but I see
    launch
    uses the
    CommonPool
    if it is implemented like this. Is there a way that this automatically inherits the parents dispatcher or should it always be used like this
    launch(coroutineContext)
    ?
    e
    • 2
    • 1
  • y

    ylemoigne

    08/31/2018, 9:44 AM
    Does this talk to anyone ?
    > Could not parse module metadata <https://jcenter.bintray.com/org/jetbrains/kotlinx/kotlinx-coroutines-core/0.25.0/kotlinx-coroutines-core-0.25.0.module>
                > Unsupported format version '0.3' specified in module metadata. This version of Gradle supports format version 0.4 only.
    e
    • 2
    • 2
  • r

    richodemus

    08/31/2018, 1:59 PM
    Can anyone recommend a good talk on coroutines? especially one that focuses more on how they work rather than how to use them 🙂
    f
    r
    • 3
    • 3
  • p

    pdegand

    08/31/2018, 3:20 PM
    My usecase is to build a lazy cache with a ConflatedBroadcastChannel where when a subscriber is suspending on
    receive()
    , some code that will send stuff into the channel is executed
    b
    • 2
    • 1
  • n

    Nikky

    09/02/2018, 11:24 AM
    i have a bit of parallel processing along the lines of
    val targetFiles = Collections.synchronizedMap(mutableMapOf<String, File>())
    val features = Collections.synchronizedList(mutableListOf<SKFeatureComposite>())
    
    val jobs = mutableListOf<Job>()
    for(...) {
       jobs += launch {
          //do work here
          targetFile[id] = someFIle
          if(feature != null) {
             features += feature
          }
       }
    }
    
    jobs.forEach { it.join() }
    is there cleaner ways to handle collecting data that lets me juggle less mutable collections ?
    d
    d
    • 3
    • 24
  • k

    khairil.ushan

    09/02/2018, 5:04 PM
    If i want to call my
    search
    function after user finish typing (by being idle for >=400ms). is this the correct way to do this with coroutines?
    fun onKeywordChanged(keyword: String) {
      keywordJob.cancel()
      keywordJob = launch {
        delay(400)
        if (!isActive) return@launch
        search(keyword)
      }
    }
    👍🏼 1
    g
    a
    d
    • 4
    • 7
  • a

    Aregev2

    09/02/2018, 6:22 PM
    compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.25.0-eap13"
    This is correct, right?
    n
    s
    • 3
    • 3
  • n

    Nikky

    09/03/2018, 1:04 AM
    so in my code currently it seems to ignore exceptions.. prints them but does not halt the app i start my main with runBlocking and do parallized wirk with launch() in a FixedThreadPoolContext one way i found to handle it is to wrap the entire code in try catch and do couroutineContext.cancel() on failures, but that seems very.. weird to stop working that suddenly
    m
    • 2
    • 2
  • n

    Nikky

    09/03/2018, 11:22 AM
    is there any better option than Collections.synchronizedList(mutableListOf()) in stdlib or in libraries ? i would feel a lot safer if i knew that i do not have any nasty ConcurrentCoModificationExceptions waiting for me due to forgetting to synchronize() on the list somewhere
    g
    b
    • 3
    • 4
  • v

    vitrox1

    09/04/2018, 1:03 PM
    hi guys, someone knows how to close a subscription from ConflatedBroadcastChannel properly? in my case for some unmanaged android behavior we openSubscription() many times so we’re creating a lot of those
    l
    • 2
    • 4
  • s

    sdeleuze

    09/04/2018, 2:22 PM
    @elizarov Do you plan to release an updated
    kotlinx.coroutines
    EAP in order to avoid the pre-release warnings with Kotlin 1.3-M2?
    i
    • 2
    • 16
  • e

    egorand

    09/04/2018, 3:00 PM
    Does anybody have experience with maintaining both coroutine-based and non-coroutine-based codebases in a library? I.e. marking a random library method with
    suspend
    is a breaking change, since the callers now have to wrap it inside a coroutine builder. Ideally I'd like library users to opt into coroutines if they decide to and be able to use the library as is if they don't, and avoid duplicating code add coroutines support. Any OS projects that do this already?
    r
    p
    +2
    • 5
    • 16
  • a

    Allan Wang

    09/04/2018, 4:07 PM
    Just to confirm, the coroutine API is already stable as of 1.3-M2 correct?
    e
    • 2
    • 1
  • r

    rocketraman

    09/04/2018, 4:36 PM
    I'm a bit confused about the dependencies of the new kotlinx-io -- the github page https://github.com/Kotlin/kotlinx-io references kotlinx-coroutines-io but this doesn't seem to exist any more?
    e
    • 2
    • 5
  • g

    Gabriel Ittner

    09/04/2018, 6:34 PM
    will there be a
    0.25.3-eap13
    ?
    e
    • 2
    • 1
  • t

    thevery

    09/05/2018, 8:29 AM
    @elizarov is there any news on https://github.com/Kotlin/kotlinx.coroutines/issues/462?
    e
    • 2
    • 1
  • i

    ilya.gorbunov

    09/05/2018, 11:41 AM
    message has been deleted
    t
    d
    +3
    • 6
    • 22
  • r

    richodemus

    09/05/2018, 2:49 PM
    Is there a way to "wake up" a coroutine that is currently suspended due to having called
    delay
    so like this:
    launch {
       println("This is called right away")
       delay(1, YEARS)
       println("I want this to happen when a criteria is met")
    }
    
    if(criteria) {
      cancelDelay()
    }
    m
    s
    +2
    • 5
    • 11
  • a

    aaverin

    09/05/2018, 3:12 PM
    Rewriting some RxJava to coroutines and replacing PublishSubject with BroadcastChannel. How can I send exception or error through BroadcastChannel?
    s
    p
    +2
    • 5
    • 20
Powered by Linen
Title
a

aaverin

09/05/2018, 3:12 PM
Rewriting some RxJava to coroutines and replacing PublishSubject with BroadcastChannel. How can I send exception or error through BroadcastChannel?
s

Seri

09/05/2018, 3:17 PM
You could handle errors like any other event and send them as a typed object
p

Paul Woitaschek

09/05/2018, 3:24 PM
How do you send exceptions through a
PublishSubject
?
l

louiscad

09/05/2018, 4:08 PM
With Kotlin 1.3, you can send
SuccessOrFailure
through a channel. Otherwise, a sealed class or similar would be great
u

uli

09/05/2018, 6:26 PM
in Rx onError should really only be used if your steam fails, not for negative, but expected results. Maping this to channels, i would say instead of onError, you just throw in the produce. As in rx this should only be used exceptionally. Otherwise follow the suggestions above, regarding typed objects for errors.
👍 1
➕ 1
a

aaverin

09/06/2018, 11:00 AM
@uli that’s was my line of throught Problem is, I don’t have
produce
– I am wrapping a 3rd party library callback. So I have a channel, and callback, that will be invoked some time in the future, and might have error inside. If it happens, I need to inform my channel subscriber that something went wrong
I also would like to leave it on channel consumer to decide what to do with the error state
This is even more complexified by bad 3rd party library design – this callback is global, so I can’t just throw an exception there
@Paul Woitaschek with
onError()
?
@louiscad Hmm. Sounds like BroadcastChannel/Channel doesn’t really map that well to PublishSubject/Subject concept. So channel consumer would then have to throw an exception in case value happened to be a failure?
p

Paul Woitaschek

09/06/2018, 11:07 AM
Then it terminates, that's usually not good
How does your code look like that you want to send exception?
a

aaverin

09/06/2018, 11:07 AM
I have a purchase callback coming from a library that can either be success or failure with a reason
My job is to hide this purchasing library completely from my end codebase
so my end application is supposed to get events, and react on them by showing, for example, error page
p

Paul Woitaschek

09/06/2018, 11:08 AM
Then mapping the event to an error code (i.e sealed class) would be the best way
I'm not sure this is built for that but you could close the channel using an exception
a

aaverin

09/06/2018, 11:09 AM
Looks like it’s the only way Still, purchasing error sounds like a bad thing to have, I wouldn’t mind Subject to unsubscribe
Well, now, how would you unit test this?
sealed class PurchaseEvent {
    object Success : PurchaseEvent()
    data class Error(val reason: String) : PurchaseEvent()
}

@Singleton
internal class ChanneledPurchaseHandler @Inject constructor() {

    val purchaseHandler = object : PurchaseHandler {
        override fun onPurchaseSuccess() {
            launch { channel.send(PurchaseEvent.Success) }
        }

        override fun onPurchaseFailure(errorCode: Int, errorMessage: String?) {
            launch { channel.send(PurchaseEvent.Error("$errorCode $errorMessage")) }
        }
    }

    val channel = BroadcastChannel<PurchaseEvent>(1)
}
ok, I was able to change channel
send
to
sendBlocking
and test was easy
l

louiscad

09/06/2018, 3:51 PM
@aaverin You can wrap the channel calls to throw when attempting to receive an error. I do something like this in my company's library BleGattCoroutines
View count: 3