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

    hmole

    06/26/2019, 5:09 AM
    I'm trying to start cancellable(synchroniously) async operation inside a suspend function(without
    CoroutineScope
    receiver). Is there a better way? Sample in a thread.
    s
    l
    • 3
    • 5
  • p

    pawelbochenski

    06/26/2019, 6:35 AM
    Hi, I’ve got mqttclient which in current implementation sends messages to Channel. Would flow be something I would benefit from, or should I stay with Channels, since mqttclient is hot source in nature?
    g
    • 2
    • 1
  • y

    Yan Pujante

    06/26/2019, 4:08 PM
    I have implemented a job queue using Rx https://github.com/ypujante/jamba-quickstart-server/blob/master/src/jvmMain/kotlin/org/pongasoft/jamba/quickstart/server/be/services/JobQueue.kt and TBH was kind of a pain (error handling, etc..)... was wondering if coroutines/channels would be easier?
    u
    • 2
    • 1
  • a

    Alexander Vtyurin

    06/26/2019, 8:03 PM
    Is there a better way to implement suspending
    while
    loop instead of this?
    while (condition) {
       ...
       delay(1)
    }
    s
    d
    e
    • 4
    • 8
  • j

    jw

    06/27/2019, 2:15 PM
    use a normal loop and invoke
    doSomething()
    directly
    ➕ 6
    r
    • 2
    • 1
  • p

    Paul Woitaschek

    06/28/2019, 9:27 AM
    Is there a flow replacement for
    <T> Observable<T> merge(Iterable<? extends ObservableSource<? extends T>> sources)
    ?
    v
    • 2
    • 1
  • d

    Dias

    06/28/2019, 1:34 PM
    what the difference from the programmer perspective will be between coroutines coming from the project loom compared to kotlin coroutines?
    s
    l
    • 3
    • 4
  • h

    haroldadmin

    06/28/2019, 5:22 PM
    What coroutine scope do you use to launch coroutines in classes that don’t have a lifecycle? I’m creating a NotificationManager class in an Android application, and I need to use coroutines for taking some database related tasks off the main thread. This class will be used as a singleton in the project via dependency injection. Should I implement the
    Coroutine Scope
    interface in it? There will be no lifecycle callback to cancel the running coroutines in this scope, though. Since a single instance of this class will be shared with the entire application, any coroutines launched in this scope will be equivalent to launching them in the global scope. So should I just avoid the ceremony and use GlobalScope in this class?
    l
    • 2
    • 4
  • u

    ursus

    06/28/2019, 7:05 PM
    I have a event bus type of stream/Flow, where Events have id. I need to replay last item of a chosen id to subscriber on subscription. If I only use replay(1) and filter { it == id } at subscriber, then only totally last item is replayed, so susbscribers who filter a different id, wont get their respective replays. I need a replay per id. (Alternative is to emit a map of all events and filter that down, but I hope this can be done more cleanly) Thanks
    s
    • 2
    • 11
  • l

    Luis Munoz

    06/28/2019, 9:57 PM
    I've implemented a class that extends CoroutineScope and does batching with flows like timeoutbuffer in reactor and not sure if I am doing the error detection correctly. It is working but can someone please look at it provide feedback and or just their opinion on what is right and wrong about it? Actually I'm not sure how to handle errors or restart the flows. Advice is appreciated, code in the thread...
    • 1
    • 1
  • g

    groostav

    06/28/2019, 11:51 PM
    Does anybody have a project with a guava event bus on it and suspending/async-ing subscribers? I would very much like to have
    @guava.Subscribe suspend fun handle(event: MyEvent)
    functions, but by default guava has no idea how to handle that. I've tried: 1. switching my tests to invoke handlers directly. This works for tests but has trouble with some of our components 2. adding an obnoxious inheritance system to try and keep a
    List<Job>
    on the event itself, that gets appended to by subscribers. This is not great. I'd be willing to take a fork of evenBus just for support for concurrent & synchronous event publication, especially if I can get it without retrofitting existing blocking java code.
    e
    • 2
    • 9
  • p

    Paul Woitaschek

    07/01/2019, 8:58 PM
    In the testing documentation: https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test It's recommended to pass the scope through the constructor:
    class Subject(val scope: CoroutineScope) {
        fun foo() {
            scope.launch {
                // launch uses the testScope injected in setup
            }
        }
    }
    But what do I actually pass in production code here?
    s
    • 2
    • 1
  • s

    streetsofboston

    07/01/2019, 10:22 PM
    Hello everyone, I’ve been struggling with how Coroutines really deal with handling exceptions… I wrote up my findings in a blog-post. Hope you like it 🙂 https://medium.com/the-kotlin-chronicle/coroutine-exceptions-3378f51a7d33?source=friends_link&amp;sk=9b069dd9a4de5542712496a10b5a29c9
    👍 3
    p
    • 2
    • 2
  • g

    georgiy.shur

    07/02/2019, 5:35 AM
    Hello, what is the proper way to handle error/success responses with new Retrofit coroutines? Back then we did it with custom adapter. But now it seems that it's not possible with corourines.
    g
    j
    +3
    • 6
    • 13
  • s

    streetsofboston

    07/02/2019, 3:04 PM
    I have a question about
    SupervisorJob
    . This code
    CoroutineScope(SupervisorJob()).launch {
        launch { 
            println("Launched Child 1")
            delay(500)
            println("Child 1 crashed")
            throw SillyException()
        }
    
        launch {
            println("Launched Child 2")
            delay(1000)
            println("Child 2 is still running")
            delay(500)
        }
    
        delay(1000)
        println("Parent is still running")
    }
    
    Thread.sleep(2000)
    prints out this:
    Launched Child 1
    Launched Child 2
    Child 1 crashed
    Exception in thread "DefaultDispatcher-worker-2 @coroutine#3" launch_exceptions.SillyException: Silly
    	at launch_exceptions.FileKt$main$1$1.invokeSuspend(File.kt:20)
            ...
    I expected only “Child 1” to crash/stop, due to the parent being a Supervisor-Job . However, I expected “Child 2" launch and the parent to continue running… especially since
    MainScope()
    is defined in a similar way…
    e
    l
    d
    • 4
    • 6
  • n

    necati

    07/02/2019, 5:48 PM
    I need a way to do this in view model with coroutines.
    Observable.interval(0, 1, TimeUnit.MINUTES)
    When I leave the page, the task should be dismissed. Any suggestions?
    l
    j
    • 3
    • 2
  • k

    kevin.cianfarini

    07/02/2019, 7:55 PM
    Is anyone using
    Flow
    instead of
    LiveData
    ? I'd like to use flow for everything but I don't know of any catches that Flow may have since I'm pretty inexperienced with it.
    m
    d
    d
    • 4
    • 3
  • u

    ursus

    07/03/2019, 8:47 AM
    How would I then trigger this from viewmodel / receive result?
    p
    s
    • 3
    • 7
  • g

    groostav

    07/03/2019, 6:46 PM
    is there a set of extension functions for
    Sequence
    that work for
    suspend
    contexts? IE i have a sequence and I want to
    map
    on it in a
    suspend
    caller
    b
    b
    • 3
    • 14
  • r

    rook

    07/03/2019, 8:31 PM
    May be a silly question, but can a
    Job
    join()
    asynchronously? I’d like to append coroutines to a job dynamically and then have it complete when it runs out of running coroutines
    b
    d
    s
    • 4
    • 7
  • b

    bj0

    07/04/2019, 1:07 AM
    AS says
    Channel operators are deprecated in favour of Flow and will be removed in 1.4
    But if my channel source is hot (network traffic), how/where should I introduce Flow? The articles I've read so far make the distinction between hot and cold data streams and claim Flow is for cold streams
    g
    • 2
    • 3
  • r

    rkeazor

    07/04/2019, 2:16 AM
    Is there a timeline to when Flow will reach stable
    l
    • 2
    • 2
  • s

    Slackbot

    07/04/2019, 3:54 AM
    This message was deleted.
    t
    d
    • 3
    • 2
  • p

    pteale

    07/04/2019, 1:47 PM
    Whats the equivalent coroutine code in 1.3 for this code..
    return async {
                val newConsent = consent.copy(createdAt = getConsent()?.createdAt)
                val uniqueId = getUniqueId().await()
    
                val consentFromApi = userServiceApi.consentApiClient.putConsent(uniqueId, newConsent).await()
    
                localStorageService.setConsent(consentFromApi)
            }
    Which should return a Deferred<Unit>
    g
    d
    • 3
    • 7
  • k

    koufa

    07/05/2019, 1:53 PM
    Hey guys, how do I build the correct way the following scenario with
    flow
    . I want to listen to text changes from an input field. The classic way would be to add a listener to the input field and respond to text changes in the callback. Now I want to get a
    flow
    which emits the current text on every text change. Do I need to use a
    channel
    that sends the text on every text change and then create a flow from the channel? I saw that there are some APIs for that on the flow documentation pages.
    j
    • 2
    • 2
  • l

    Luis Munoz

    07/05/2019, 5:10 PM
    How do I wrap some callback inside an async or suspend function so I can return my own value. This is what I'm trying ....
    s
    d
    • 3
    • 3
  • p

    Pere Casafont

    07/08/2019, 11:25 AM
    When I add the
    suspend
    modifier to a function that I know it will take long to compute, intellij bugs me with the
    Redundant 'suspend' modifier
    inspection. Am I doing something wrong? All I want is to force this function to be called from a coroutine scope...
    g
    e
    b
    • 4
    • 9
  • a

    addamsson

    07/08/2019, 12:33 PM
    I have a question about coroutines. What is the fastest way to restrict access to a shared resource? I've checked this article: https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html but it doesn't detail the performance characteristics of the solutions
    b
    d
    b
    • 4
    • 21
  • l

    Luis Munoz

    07/08/2019, 4:20 PM
    Anyone can an article that deep dives into delays, ticker, and other timing related functions with coroutines. Not sure how efficient they are. I know they don't block a thread but how do they know when the delay is over and put you back on the same thread especially when you have many and maybe that thread is now busy? Does it have some sort of event loop that keeps checking the current time with a list of functions that are suspend?
    z
    • 2
    • 1
  • m

    Marcelo Hernandez

    07/08/2019, 5:16 PM
    Been converting Rx
    Singles
    ,
    Maybes
    , and
    Completables
    to
    suspend
    functions. I feel that with Rx, error handling is pretty much
    try/catch(Throwable)
    behind the scenes. So when switching over to coroutines, one might "naively" start using
    runCatching { ... }.onSuccess { ... }.onFailure { ... }
    or basic
    try/catch(Throwable)
    . The issue with this is that a
    CancellationException
    will also be caught when attempting to cancel a coroutine. Does this mean that before refactoring to
    suspend
    functions, one should begin defining custom, domain-specific Exceptions or leverage some sort of
    Result
    type in order to avoid
    try/catch(Throwable)
    ?
    l
    s
    +2
    • 5
    • 12
Powered by Linen
Title
m

Marcelo Hernandez

07/08/2019, 5:16 PM
Been converting Rx
Singles
,
Maybes
, and
Completables
to
suspend
functions. I feel that with Rx, error handling is pretty much
try/catch(Throwable)
behind the scenes. So when switching over to coroutines, one might "naively" start using
runCatching { ... }.onSuccess { ... }.onFailure { ... }
or basic
try/catch(Throwable)
. The issue with this is that a
CancellationException
will also be caught when attempting to cancel a coroutine. Does this mean that before refactoring to
suspend
functions, one should begin defining custom, domain-specific Exceptions or leverage some sort of
Result
type in order to avoid
try/catch(Throwable)
?
l

louiscad

07/08/2019, 6:33 PM
There are multiple solutions to this problem. One is to have an empty
catch(ignored: CancellationException)
first, or from which you rethrow (important if there's only custom suspending functions that don't check for cancellation). Another is to catch only the expected exceptions (might be risky if you don't know what can be thrown). You can also check
e is CancellationException
and rethrow it.
m

Marcelo Hernandez

07/08/2019, 6:46 PM
Thank you for your reply!
If I understand correctly, if I were to try and port over existing non-Observable Rx code, with minimal changes, it would go from
doRxAsyncWork()
    .subscribeOn(...)
    .observeOn(...)
    .subscribe(
        { ... },
        { error -> // perform error handling }
    )
to
try {
    doSuspendingWork()
} catch (ex: CancellationException) {
    throw ex
} catch (ex: Throwable) {
    // perform error handling
}
:yes: 1
Thanks again! IMO, this does not look as nice as Rx. It does become a harder sell for people who are perfectly happy with RxJava.
One can probably define their own custom
runCatching
utility that catches and re-throws the
CancellationException
.
s

streetsofboston

07/08/2019, 7:30 PM
Yup, I found the same issue. It seems Kotlin here is almost forcing you to never catch exceptions with a broad/wide net. It is indeed better to catch specific exceptions instead of
Exception
, or
Throwable
, etc. In this case it is somewhat forced on you to catch specific ones only
m

Marcelo Hernandez

07/08/2019, 7:37 PM
In general, it has always been good practice to catch specific exceptions. Unfortunately, Rx made it way to easy to overlook this. The issue now is trying to refactor existing non-
Observable
Rx code to
suspend
functions with minimal effort.
p

Paul Woitaschek

07/08/2019, 8:08 PM
Or you don't go the minimal efford way and find erros in your code 😉
☝️ 1
m

Marcelo Hernandez

07/14/2019, 8:16 PM
It seems
Flows
will be getting a
catch
operator that properly handles
CancellationExceptions
. “Exceptions in Kotlin Flows” by Roman Elizarov https://link.medium.com/AenSuqlckY
@elizarov any chance we'll be getting a
runCatching
variant for non-
Flow
suspend
code that also takes
CancellationExceptions
into account?
s

Stephane Maldini

07/15/2019, 10:07 PM
I think you mischaracterized “error handling” as transparent in rx. There are explicit operators to force you to address them because they might happen asynchronously and they don’t suspend/resume to rethrow in the current thread. You actually can’t not deal with errors
i expect Flow to catch up and have a similar operator vocabulary soon enough
View count: 4