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

    zak.taccardi

    04/08/2019, 6:14 PM
    what’s the recommend pattern to launch a non-cancellable coroutine from within a cancellable
    CoroutineScope
    ?
    a
    s
    • 3
    • 14
  • l

    louiscad

    04/08/2019, 7:44 PM
    A while ago, I made a function to race coroutines (winner cancels all the losers) thanks to your help, and now that I'm planning to add it to a library since it's not in kotlinx.coroutines, I'd like to have your thoughts on its name, and ideas if any. Here's that function, currently named `raceOf`:
    suspend fun <T> raceOf(vararg racers: suspend CoroutineScope.() -> T): T = coroutineScope {
        select<T> {
            @UseExperimental(ExperimentalCoroutinesApi::class)
            val racersAsyncList = racers.map { async(start = CoroutineStart.UNDISPATCHED, block = it) }
            racersAsyncList.forEach { racer ->
                racer.onAwait { resultOfWinner ->
                    racersAsyncList.forEach { deferred -> deferred.cancel() }
                    return@onAwait resultOfWinner
                }
            }
        }
    }
    s
    s
    • 3
    • 2
  • s

    serebit

    04/08/2019, 7:57 PM
    Got a question, a choice between two possible answers. The end result should be a system that can halt for a certain period of time if one of the channels within that system receives a signal to do so. The scenario: Several rendezvous channels are run simultaneously, each within their own coroutine, and each corresponding to an API route. When a request for that route is called, it is sent to the appropriate channel, which processes the request and returns the response via a second channel. After this, it checks for a route-specific ratelimit header, and if it finds this header, it delays for that period of time before processing the next request. The problem: The system also needs to be able to tell every channel to halt for that period of time IF a specific “global” header is present in a response. Solution 1️⃣ Hold a nullable
    BroadcastChannel<Unit>
    on the top level. Every channel will call subscribe and receive on this channel at the start of processing a request. The variable will usually be null, but if a “global” header is received, it will be set to
    BroadcastChannel(1)
    , and the channel where this header was received will delay for the given amount of time before setting the variable to null and calling
    send(Unit)
    , unsuspending all the waiting channels. Solution 2️⃣ Hold the global delay target as a unix millis, or null, at the top level. Every channel will delay for the amount it time it takes to get to that unix millis if it is not null. If a channel receives the global header, it sets the global unix millis and delays for that period of time before setting it back to null.
    1️⃣ 1
    2️⃣ 1
    o
    • 2
    • 12
  • s

    Sam

    04/08/2019, 10:01 PM
    Why does launch builder always adds Job to the new scope even when the current scope (used to launch a coroutine) uses a SupervisorJob?
    g
    • 2
    • 41
  • b

    bloder

    04/09/2019, 2:32 AM
    Hey Guys! Is there a way to do concurrency using the same coroutine context?
    async
    is not working (newbie question probably)
    g
    • 2
    • 51
  • s

    sdeleuze

    04/09/2019, 9:19 AM
    About https://kotlinlang.slack.com/archives/C0BJ0GTE2/p1554754893034600, is it possible to use
    Flow
    for hot streams as well like where we use
    Flux
    or
    Flowable
    for these use cases? If yes what are the pros/cons compared to channels?
    e
    • 2
    • 1
  • j

    jakub.dyszkiewicz

    04/09/2019, 12:06 PM
    Hello, I’m experimenting with Coroutines. Is there any abstraction to do something similar as
    .sample(Duration)
    ? https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#sample-java.time.Duration- on channel. I’d like to throttle consumer of channel to process the latest data not often than every 1s
    • 1
    • 1
  • v

    v0ldem0rt

    04/09/2019, 4:06 PM
    So if I am inside a non-suspend function (that was invoked by suspend fun) how can I access coroutineContext without adding suspend to signature of function
    f
    l
    g
    • 4
    • 6
  • v

    v0ldem0rt

    04/09/2019, 4:08 PM
    I have some context data as coroutineContext element that I want to access inside a function without changing it's signatures
    s
    • 2
    • 1
  • r

    Robert Jaros

    04/09/2019, 5:25 PM
    Why are almost all operators on Channels marked as obsolete, but the simple ".map" is not?
    g
    • 2
    • 5
  • r

    rrva

    04/09/2019, 5:27 PM
    I'm looking into replacing a server-side app (kind of an API gateway) which uses RxJava with coroutines instead. Often, there are calls across 7+ different microservices, which are managed using Observables (emitted by Hystrix), which really are Single<T>, i.e. they are not reactive streams but rather emit a single value. The reactive streams are more used for orchestrating parallel requests rather than that the async nature of these calls are the real benefit. What kind of patterns for coroutines exist for replacing for example, Observable.zip, when all that you zip are streams emitting single values? Just await() ?
    b
    • 2
    • 1
  • w

    wrover

    04/10/2019, 6:51 AM
    Hi! I wonder if there is a way to adopt the underlying resource closing interrupting approach to deal with blocking method calls like we do in Java in couroutines? I tried to use
    Continuation#invokeOnCancellation
    from
    suspendCancellableCoroutine
    but, obviously, it doesn't work this way.
    g
    • 2
    • 9
  • s

    sdeleuze

    04/10/2019, 8:02 AM
    I have a Coroutines extension leveraging some Java methods specified as
    suspend fun <T : Any> RowsFetchSpec<T>.awaitOne(): T = one().awaitSingle()
    but when it used, type inference shows
    T!
    , what did I miss? I have specified that
    T
    extends non nullable
    Any
    so I would expect return type
    T
    .
    d
    • 2
    • 8
  • o

    Olekss

    04/10/2019, 12:52 PM
    Is_this_correct_usage_of_structured_concurrency.txt
    t
    • 2
    • 1
  • a

    azeDevs

    04/10/2019, 1:03 PM
    What is the simplest implementation of a coroutine that runs a function on an interval timer in Kotlin/Native? I'm only finding solutions for Kotlin/JVM so far. My end goal is to pull data 30 times per second and update my GUI with it. If further context helps, the application is built with Cinterop for Windows and my GUI is built using: https://github.com/msink/kotlin-libui
    p
    • 2
    • 1
  • o

    oshai

    04/10/2019, 2:27 PM
    Is anyone aware of a cache utility (like guava loading cache) that works with coroutines? (ie has suspending methods, not returning deferred) I found the following solutions, but none of them do that: - https://stackoverflow.com/questions/53558215/guava-loadingcache-with-kotlin-coroutines - https://github.com/epam/CoroutinesCache
    s
    s
    • 3
    • 4
  • i

    igorvd

    04/10/2019, 6:35 PM
    Sorry if this was already asked. There's an way that I can ignore the
    delays
    from coroutines in android espresso testing?
    s
    d
    • 3
    • 3
  • d

    dewildte

    04/10/2019, 7:08 PM
    Could use a Flow<T> to replace a LiveData?
    e
    f
    • 3
    • 8
  • b

    Brandon Trautmann

    04/11/2019, 1:42 AM
    message has been deleted
    s
    • 2
    • 1
  • d

    Dariusz Kuc

    04/11/2019, 5:54 AM
    hello, I got a prototype bean that is created at runtime based on some input parameters. Within the prototype bean I got multiple methods that accept value (and some others that dont) that should be computed just once (as it is pretty expensive). Since I don't want to incur the initialization penalty if I'm not going to be calling a method that needs it I was using
    by lazy
    . I'm migrating now to coroutines was wondering whats the proper way to update
    by lazy
    to call suspendable function. Any thoughts on how to make this better?
    Untitled.txt
    m
    • 2
    • 7
  • r

    Robert Jaros

    04/11/2019, 8:18 AM
    Is there any roadmap for coroutines 1.2? When should we expect stable release?
    ➕ 5
    a
    • 2
    • 1
  • g

    GarouDan

    04/11/2019, 11:24 AM
    Hi guys, let me ask you a simple question. When using co-routines, will we be using all cpus available always?
    🇳🇴 4
    l
    t
    +3
    • 6
    • 9
  • s

    Stephane M

    04/11/2019, 11:51 AM
    Hi all, quick question for a newbie. I have a
    List<Node>
    . I want to run a repeated background job on each node in that list (independently), that fetches some data from a URL and mutates the node state at each iteration. At some point I want to be able to stop the entire job altogether. Do you have any pointers? I'm a bit lost with coroutines
    t
    • 2
    • 1
  • m

    Marko Mitic

    04/11/2019, 4:30 PM
    Hi, are channels still experimental? I'm thinking of using it for a SDK and experimental API won't work for me. Documentation says channels are experimental, code tags only some subset of channel API as experimental.
    d
    • 2
    • 1
  • o

    obobo

    04/11/2019, 4:35 PM
    Basically I have a situation where I want a 'best-effort' behavior, but with nested scopes. Do I need to declare a scope with SupervisorJob at each scope creation? I assume yes because that seems more predictable (but more verbose), but I want to make sure.
    d
    b
    • 3
    • 25
  • p

    pardom

    04/11/2019, 4:58 PM
    Is there a coroutines release planned to coordinate with today’s 1.3.30 release?
    d
    • 2
    • 1
  • i

    igorvd

    04/11/2019, 6:18 PM
    how to handle exceptions while using
    Flow
    ? I was looking at the
    onErrorCollect
    and
    onErrorReturn
    but I'm not sure how to use it. I'm using the simple
    try-catch
    now, but I was wondering if it already has an API for that. My usecase is that I'm trying to write an offline-first approach: I first search on local storage and emit what it has, then I look online and emit the itens that aren't cached yet . I want to handle the exceptions (mostly networking ones) only if the local storage was empty in the first place.
    l
    • 2
    • 7
  • n

    nulldev

    04/12/2019, 9:32 AM
    So I've been playing with the new Flow stuff and from what I've seen, when I skimmed through the code, none of the built in functions seem to do any cancellation checks? Example:
    val job = launch(Dispatchers.Default) {
        val result = myGiantList.asFlow().filter {
            cpuBoundFilter(it)
        }.toList()
    }
    job.cancel()
    If I don't do any cancellation checks in
    cpuBoundFilter
    , the flow will continue to filter through everything even though it has been cancelled.
    v
    e
    • 3
    • 9
  • z

    zak.taccardi

    04/12/2019, 4:58 PM
    if you use
    actor.offer(message)
    (instead of
    actor.send(message)
    when the
    actor(capacity = Channel.UNLIMITED)
    , is there locking involved?
    d
    g
    • 3
    • 8
  • v

    Vsevolod Tolstopyatov [JB]

    04/12/2019, 6:31 PM
    📣 📣 📣
    kotlinx.coroutines
    1.2.0 is here! Changelog: * Kotlin 1.3.30 * New API:
    CancellableContinuation.resume
    with
    onCancelling
    lambda to consistently handle closeable resources. * Flow improvements, including new operators, better documentation and RxJava integration. Note that it is not leaving its experimental status yet. Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.2.0
    😒uspend: 20
    🎉 15
    s
    e
    • 3
    • 4
Powered by Linen
Title
v

Vsevolod Tolstopyatov [JB]

04/12/2019, 6:31 PM
📣 📣 📣
kotlinx.coroutines
1.2.0 is here! Changelog: * Kotlin 1.3.30 * New API:
CancellableContinuation.resume
with
onCancelling
lambda to consistently handle closeable resources. * Flow improvements, including new operators, better documentation and RxJava integration. Note that it is not leaving its experimental status yet. Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.2.0
😒uspend: 20
🎉 15
s

sdeleuze

04/12/2019, 8:19 PM
Congrats. Could you give us more details about the reasons of « flatMap, merge and concatenate are replaced with flattenConcat, flattenMerge, flatMapConcat and flatMapMerge. » ?
e

elizarov

04/13/2019, 7:42 AM
The chief reason is that we have conflicting evidence on what
flatMap
is expected to do (should it concat or merge), so this way we can defer making this decision.
s

sdeleuze

04/25/2019, 1:32 PM
@elizarov What about
concatMap
instead of
flatMapConcat
and
flatMap
instead of
flatMapMerge
?
e

elizarov

04/25/2019, 5:46 PM
That's a possibility if in the end we decide that
flatMap
should do
flatMapMerge
. The downside of that decision is that if you copy-and-paste a code written with
Sequence
to
Flow
then suddenly it starts working differently, because
flatMap
for sequences is
flatMapConcat
.
View count: 3