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

    zak.taccardi

    11/18/2019, 5:27 PM
    I’m curious if this example is my fault, or if it’s a coroutines issue - but I want to get an easy to debug stacktrace https://github.com/Kotlin/kotlinx.coroutines/issues/1661
    b
    • 2
    • 17
  • s

    SrSouza

    11/18/2019, 9:48 PM
    Why Actors is not multiplataform ?
    s
    s
    +2
    • 5
    • 9
  • p

    Paul Woitaschek

    11/19/2019, 8:13 AM
    How can I cancel something using another scope? I have a class that has it's own lifecycle scope. Now when someone calls a suspend funtion on that class I want that function to get cancelled when the scope of the class is cancelled.
    t
    s
    • 3
    • 16
  • p

    Patrick

    11/19/2019, 1:52 PM
    I’m seeing the following problem: If I cancel a coroutine with a specific exception as the cause on the JVM, I can access that cause with exception.cause. But if I run the same code on K/N, the cause is null. Any ideas how to solve this? Ironically, the exception.message still states, that it was caused by the correct exception, I just don’t have access to it.
    e
    • 2
    • 2
  • j

    jeff

    11/19/2019, 6:34 PM
    (Update from earlier): I want to cache/share a Flow (like rx's replay)? E.g. I have
    flow { 
        emit(expensiveNetworkOperation1())
        emit(expensiveNetworkOperation2())
        emit(expensiveNetworkOperation3())
    }
    and I want to collect that flow repeatedly, without repeating the expensive operations. Here's my solution. Feedback? Gotchas I'm missing?
    /**
     * Collects the upstream source a single time, and sends cached values to any future collectors
     */
    fun <T> Flow<T>.replay(): Flow<T> {
    
        val upstream = this
    
        return object : AbstractFlow<T>() {
    
            val isFinished = AtomicBoolean()
            val isCollecting = AtomicBoolean()
    
            val values = mutableListOf<T>()
    
            override suspend fun collectSafely(collector: FlowCollector<T>) {
                coroutineScope {
    
                    // Collect the upstream flow (but only once) and remember the values it emits
                    if (!isCollecting.getAndSet(true)) {
                        launch {
                            upstream.collect { values += it }
                            isFinished.set(true)
                        }
                    }
    
                    // Create a downstream flow that just emits cached values
                    val downstreamFlow = flow {
                        var i = 0
                        while (!isFinished.get()) {
                            while (i < values.size) {
                                emit(values[i])
                                i++
                            }
                            delay(1)
                        }
                    }
    
                    collector.emitAll(downstreamFlow)
                }
            }
        }
    }
    a
    l
    • 3
    • 5
  • s

    Slackbot

    11/19/2019, 11:11 PM
    This message was deleted.
    s
    s
    • 3
    • 2
  • h

    henrikhorbovyi

    11/20/2019, 12:48 PM
    [
    QUESTION
    ] Hello mates, I always hear people saying that RxJava is really powerful and coroutines it's a lighter solution. And they say that the situation to use RxJava is when you should use all those Rx operations (e.g.
    transform, map, etc
    ). Thinking about this I was wondering if it's possible to do the same only with Coroutines and pure Kotlin, and if not, what is it so powerful in Rx?
    c
    s
    +2
    • 5
    • 20
  • b

    bod

    11/20/2019, 2:47 PM
    Hello, World! I've been using coroutines for about a year now, but am still unclear (or even confused) about a few details. The same thing happened to me with Rx, until I read a very good book about it and it all became clear. Can anyone recommend a book about Coroutines?
    j
    • 2
    • 4
  • a

    Animesh Sahu

    11/20/2019, 3:35 PM
    If i was intended to cancel the scope then how to handle/suppress
    JobCancellationException
    at once?
    s
    • 2
    • 9
  • v

    vineethraj49

    11/20/2019, 4:12 PM
    is there a way to schedule a block of code to run on a block completion when run with
    withContext
    ? (I’m trying to time some functions)
    r
    d
    s
    • 4
    • 10
  • d

    dave08

    11/20/2019, 4:43 PM
    Is there currently a way to implement some kind of
    share
    operator on
    Flow
    (at least in the meantime until it shows up in the library)? As in https://github.com/Kotlin/kotlinx.coroutines/issues/1261 ...
    broadcastIn
    and
    asFlow
    is probably hot... so a fast upstream might lead to lost emissions unless a buffer is properly configured...
    s
    • 2
    • 6
  • p

    pardom

    11/20/2019, 6:30 PM
    Is there a release for 1.3.60 coming soon?
    d
    • 2
    • 2
  • j

    jimn

    11/20/2019, 8:14 PM
    https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html#dispatchers-and-threads appears to be the starting point i am looking for, and i find "newSingleThreadContext". I think to myself that having threads with CPU affinity is good for breaking a memory mapped file into N lines/CPU chunks. upon clicking on that link i read bold letters: "*NOTE: This API will be replaced in the future.*" In c++ there is openMP, and a pragma lets you simply annotate a loop to parralelize it. Is there something so simple I am missing from the coroutines docs?
    o
    c
    • 3
    • 10
  • k

    kevin.cianfarini

    11/20/2019, 10:17 PM
    what is the entity responsible for resuming a coroutine? Is it a
    Dispatcher
    ?
    o
    • 2
    • 7
  • y

    Yauhen Pelkin

    11/21/2019, 9:26 AM
    Is there any way to combine flow items in to list without termination?
    p
    • 2
    • 8
  • j

    jeggy

    11/21/2019, 5:57 PM
    Hi all, I'm trying to write a coroutine based DataLoader to be used on within a GraphQL implementation. I've made a simple Slideshow of what I want to achieve: https://docs.google.com/presentation/d/1lh5MzqM36xDvIkDsK8NGIlmfxq5uuPXbgAT4Kf9CjLw/ Anyone that could guide me to which coroutine tools I should use for something like this?
    s
    • 2
    • 1
  • r

    rocketraman

    11/21/2019, 11:12 PM
    What is the impact of running the coroutines debug agent in production? I find it really useful to do
    kill -5
    to get insight into the running coroutines, but always see the "do not use in production" warnings.
    o
    v
    • 3
    • 5
  • u

    ubu

    11/22/2019, 6:55 AM
    Hello there. This is an Android-related question. I need to load images from some remote source. These images are
    BLOB
    objects. I implemented a service that fetches these images by leveraging the power of Kotlin
    Coroutines
    . This service is quite simple, it just exposes a
    suspend fun
    . I used it as one-shot operation inside a
    ViewModel
    , so the scoping here was easy. Now I need to use this image loader inside a
    RecycerView
    . So the scoping there gets tricky: how do I manage a
    CoroutineScope
    inside a
    RecyclerView
    ? As far as I understand, I cannot use
    Glide
    ,
    Picasso
    or
    Coil
    , since it is bound to uri/url image sources. So I need to implement it myself. Where do I start? Should I somehow use a
    LifecycleOwner
    in order to get that scoping feature? Any help will be very appreciated. 🏅
    w
    a
    • 3
    • 4
  • j

    Jason

    11/22/2019, 9:21 AM
    Hi all A little confused about thread in couroutine. Basically, we all use
    <http://Dispatchers.IO|Dispatchers.IO>
    for call api from network. But I am confused that where need we specified the dispatcher. For example: I have a UserViewModel class and FetchUserUseCase class.
    Pattern 1
    1. FetchUserUseCase.kt
    suspend  fun fetch(): UserResponse {
       return runCatching {
                withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                    clientApi.get()
                }
            }
    }
    2. UserViewModel.kt
    fun fetch() {
       viewModelScope.launch {
         fetchUserUseCase.fetch()
       }
    }
    Pattern 2
    1. FetchUserUseCase.kt
    suspend  fun fetch(): UserResponse {
       return coroutineScope {
              clientApi.get()
       }
    }
    2. UserViewModel.kt
    fun fetch() {
       viewModelScope.launch {
          runCatching {
             withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
               fetchUserUseCase.fetch()
             }
          }
       }
    }
    Above 2 way of writing is the same ? Where need we specified dispatcher ? ViewModel or UseCase
    e
    d
    +2
    • 5
    • 11
  • l

    louiscad

    11/22/2019, 9:50 AM
    Question: why hasn't 1.3.2 for Kotlin (Native) 1.3.60 been published as just 1.3.3 instead of 1.3.2-1.3.60? The versioning scheme looks more complicated than it should IMHO.
    👎 2
    ➕ 1
    d
    d
    • 3
    • 6
  • a

    Animesh Sahu

    11/22/2019, 11:18 AM
    Is there some issue with
    org.jetbrains.kotlinx:kotlinx-coroutines-io-jvm:0.1.16
    ?
    o
    l
    • 3
    • 4
  • a

    Animesh Sahu

    11/22/2019, 12:19 PM
    how to create a coroutine scope inheriting parent context but does not cancel parent scope if it was cancelled
    o
    • 2
    • 3
  • l

    Lulu

    11/23/2019, 3:33 AM
    I have a map that is going to be used by multiple coroutines; its entries will be read and modified. How to make sure this map is thread-safe? I came across mutex and atomics but I'm not sure what's the difference between them. I know
    Mutex
    uses atomics internally too and that made me more confused. I also don't fully understand how atomics work in the first place, like in what case would they lock the object? Would putting my map in an atomic guarantees the operations performed will be synchronized? etc
    o
    u
    j
    • 4
    • 14
  • k

    koufa

    11/23/2019, 1:25 PM
    Hey I have a question about
    callbackFlow
    again. How would you review following code:
    fun TextView.onTextChange() = callbackFlow {
        val listener = addTextChangedListener { text ->
            if (text != null) {
                offer(text.toString())
            }
        }
        awaitClose { removeTextChangedListener(listener) }
    }
    d
    d
    • 3
    • 3
  • s

    sajadgarshasbi

    11/23/2019, 9:55 PM
    hi, how you deal with lifecycle-aware
    CoroutineScope
    inside a compound view? is safe that pass
    LifecycleScope
    from
    Fragment
    to view? or i have to handle that with lifecycle events?
    s
    f
    g
    • 4
    • 6
  • d

    Dan Lowe

    11/24/2019, 8:01 AM
    I'm looking for a way to subscribe to a conflated
    BroadcastChannel
    but ignore any items that may already be in that channel at the time of subscription. Is this possible? (example in thread)
    o
    • 2
    • 10
  • a

    Alexey V Golubev

    11/24/2019, 9:31 AM
    What is the right way to get a count of pending messages in actor’s “mailbox” from outside? Should I expose its
    ReceiveChannel
    and do something like
    channel.asFlow().count()
    ?
    b
    • 2
    • 2
  • a

    asad.awadia

    11/24/2019, 3:55 PM
    does wrapping blocking calls
    withContext(<http://Dispatchers.IO|Dispatchers.IO>)
    stop my threads from getting 'blocked'?
    s
    l
    • 3
    • 7
  • a

    asad.awadia

    11/24/2019, 3:56 PM
    If I launch a bunch of them will all my threads eventually get hung? because at the end of the day they are blocking calls inside the withContext?
    a
    • 2
    • 1
  • r

    rrva

    11/25/2019, 4:38 PM
    if I want to implement the bulkhead pattern in kotlin, with an old-fashioned blocking http client (OkHttp/feign), what is an idiomatic way to do it in kotlin? A channel with a coroutinecontext backed by a fixed threadpool and ThreadPoolExecutor.AbortPolicy() ?
    w
    s
    +2
    • 5
    • 9
Powered by Linen
Title
r

rrva

11/25/2019, 4:38 PM
if I want to implement the bulkhead pattern in kotlin, with an old-fashioned blocking http client (OkHttp/feign), what is an idiomatic way to do it in kotlin? A channel with a coroutinecontext backed by a fixed threadpool and ThreadPoolExecutor.AbortPolicy() ?
w

withoutclass

11/25/2019, 4:50 PM
I'm not familiar with bulkhead but if you want to limit the threads used to handle the work then a FixedThreadPool would be the way to go imo
r

rrva

11/25/2019, 4:55 PM
I want extra work to be rejected when the thread pool is empty (after queueing for a thread to run on with a configurable timeout)
w

withoutclass

11/25/2019, 4:57 PM
You...want work to be thrown away when your thread pool has no work to do?
s

Steve

11/25/2019, 5:49 PM
Other way around. Sounds like they want work to be thrown away when they don't have any open threads to do it.
w

withoutclass

11/25/2019, 6:57 PM
I agree that's likely the intention, but I can't assume, so that's why I asked
d

Dico

11/26/2019, 1:03 AM
I would use a number of coroutines equal to the number of threads you want, with a shared Channel of tasks that has a maximum capacity. Then offer tasks to the channel and loop it on the workers.
Schedule it all on the default dispatcher
s

spand

11/26/2019, 5:55 AM
I think in coroutines you would rely on normal backpressure and use a timeout to detect too much work
Have you looked at resilience4j-kotlin ?
View count: 22