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

    Mark

    08/07/2020, 1:01 PM
    Suppose I have a flow of search results, where each emitted item is a single search result item (i.e. the flow needs to be collected into a list which forms the search results). Is there a recommended pattern for how to control the collection of this flow from an Android recyclerview adapter? For example, so that items are collected as the user scrolls down the recyclerview perhaps prefetching 5-10 items ahead of the last visible item.
    i
    8 replies · 2 participants
  • d

    darkmoon_uk

    08/07/2020, 3:16 PM
    Anyone using
    kotlinx-coroutines-test:1.3.8-1.4.0-rc
    for JS with success? I get resolution errors.
    m
    j
    6 replies · 3 participants
  • t

    tseisel

    08/08/2020, 7:56 AM
    I have a suspend function that executes a long async operation that should periodically report progress to the caller. According to you, what would be the best way to model that ? 1️⃣
    suspend fun doWork(progress: (Progress) -> Unit)
    2️⃣
    fun doWork(): Flow<Progress>
    3️⃣
    fun doWorkIn(scope: CoroutineScope): StateFlow<Progress>
    4️⃣ Anything else (please explain in comments !)
    1️⃣ 1
    2️⃣ 12
    g
    e
    +2
    7 replies · 5 participants
  • j

    janvladimirmostert

    08/08/2020, 10:25 AM
    Intellij complains that i'm using an inappropropriate blocking call, is it fine if it's inside a Dispatchers.io context, in other words, can i ignore this warning ?
    m
    2 replies · 2 participants
  • r

    rnentjes

    08/08/2020, 12:39 PM
    Anyone encountered this problem?: Failed to find Premain-Class manifest attribute in /home/rnentjes/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-core-metadata/1.3.8-1.4.0-rc/d478e974d38e2582a68f945f739dc7a7d4b2c3ed/kotlinx-coroutines-core-metadata-1.3.8-1.4.0-rc.jar Error occurred during initialization of VM agent library failed to init: instrument There is indeed no Premain-Class manifest attribute in that file, but this just started happening and I don't think I updated or changed anything. (edited)
    1 reply · 1 participant
  • r

    Rohan Maity

    08/08/2020, 3:20 PM
    I am using BroadcastChannel as Flow But it is not receiving anything in collect
    tunnel.pipe.send("LOPI")
    
                tunnel.pipe.asFlow().flowOn(Dispatchers.Main).collect {
    
                    tvPUI.text = it.toString()
                }
    
                delay(2000)
    
                tunnel.pipe.send("HOLA")
    t
    w
    +1
    16 replies · 4 participants
  • r

    raniejade

    08/09/2020, 3:48 AM
    Is there still no plans in supporting suspendable properties/delegates (https://youtrack.jetbrains.com/issue/KT-15555) ?
    e
    4 replies · 2 participants
  • h

    Hakob Vardanyan

    08/09/2020, 10:41 AM
    Hello community, hope you all doing well. I am getting compilation error by this code. This code written in BaseFragment, and I am trying to use it in the child. The error I am getting is:
    e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't inline method call 'collectInMainBy' into
    So why it can’t be inlined?
    inline fun <reified T> Flow<T>.collectInMainBy(
        crossinline onCollect: suspend (T) -> Unit,
        crossinline onFailure: suspend (Throwable) -> Unit = { Timber.e(it, tag) }
    ) {
        onEachCatching(onCollect, onFailure).launchInMain(lifecycleScope)
    }
    
    inline fun <reified T> Flow<T>.onEachCatching(
        crossinline onEach: suspend (T) -> Unit,
        crossinline onFailure: suspend (Throwable) -> Unit
    ) : Flow<T> {
        return onEach {
            onEach(it)
        }.catch {
            onFailure(it)
        }
    }
    
    fun <T> Flow<T>.launchInMain(scope: CoroutineScope): Job = scope.launch(Dispatchers.Main) {
        collect()
    }
    Call side:
    buttonProceed.clicks().collectInMainBy(
        onCollect = { viewModel.proceedButtonClicked() }
    )
    k
    3 replies · 2 participants
  • l

    Lukas Lechner

    08/10/2020, 8:12 AM
    Hi! Why is this coroutine here that uses Thread.sleep() not cancelled?
    fun main() = runBlocking {
    
        val job = launch {
            repeat(5) { index ->
                println("operation number $index")
                ensureActive()
                Thread.sleep(100)
            }
        }
        delay(150)
        job.cancel()
    
    }
    o
    t
    6 replies · 3 participants
  • s

    Sudhir Singh Khanger

    08/10/2020, 10:53 AM
    I am running a network call as follows. Repository
    fun home(): Flow<HomeResponse> =
            flow { emit(ApiService.home()) }.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
    ViewModel
    @ExperimentalCoroutinesApi
    fun home() {
        viewModelScope.launch {
            repository.home()
                .onStart { _homeLiveData.postValue(Resource.loading(null)) }
                .catch { _homeLiveData.postValue(Resource.error(it.message ?: "", null)) }
                .collect { _homeLiveData.postValue(Resource.success(it)) }
        }
    }
    Is there anything built-in in Flow that would ignore the repeated calling of
    home()
    method and let the existing request fail or reach success?
    w
    z
    3 replies · 3 participants
  • n

    Ningappa Moodi

    08/10/2020, 11:12 AM
    coroutine delay vs handler post delay , which one to use ?
    t
    t
    +1
    4 replies · 4 participants
  • r

    Rohan Maity

    08/10/2020, 12:03 PM
    Could I write suspend functions using kotlinpoet ?
    j
    1 reply · 2 participants
  • p

    Pacane

    08/10/2020, 6:42 PM
    Is it a normal behaviour that if I do
    // This is in a loop
    val e = async {
      writeFileToDisk()
    }
    filesBeingWritten.add(e)
    
    //somewhere else 
    filesBeingWritten.awaitAll()
    Is much slower than this
    // This is in a loop
    writeFileToDisk()
    where
    writeFileToDisk()
    is a suspending function calling
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
      val get = Paths.get(imageFilename)
      Files.write(get, bytes)
    }
    And by "slower" I mean it never seems to even complete..? Is there a limitation / maximum amount of Deferred objects we can await at a same time?
    o
    d
    +3
    25 replies · 6 participants
  • s

    Sam Garfinkel

    08/10/2020, 8:50 PM
    Is there a way to extend or modify the
    delay
    duration of a suspended coroutine from another coroutine?
    s
    c
    3 replies · 3 participants
  • r

    Rechee Jozil

    08/10/2020, 11:40 PM
    so usually in my code when I handle exceptions in a suspend function, I always first check if the exception is a cancellation exception before trying to log or otherwise. If it's CancellationException I just rethrow. Is this what others do? Is there a more... idiomatic/simple way to do this? It's a very common pattern for me (or maybe I'm just handling things incorrectly).
    o
    2 replies · 2 participants
  • v

    vineethraj49

    08/11/2020, 12:57 AM
    is it possible to create a limiting dispatcher within an existing dispatcher? I'm trying to figure out a way to have say, max(5) threads of Dispatchers.IO as another dispatcher, which I can use in a standalone manner (one way would be
    launch
    and listen on a channel? with the launch being on the dispatcher?)
    o
    1 reply · 2 participants
  • m

    Manuel Pérez Alcolea

    08/11/2020, 3:44 AM
    I've used coroutine frameworks in a few languages but they worked exclusively in a single thread. I noticed a dispatcher can have a pool of many threads (instead of a single one) - that makes me think that "regular" synchronization from my part is required (if there's a race condition) which feels unusual to me (being single threaded, you only need to worry about race conditions only if a function is suspended somewhere.) Not really technical question: how often do you use these "multi-threaded" dispatchers? Is it common?
    o
    s
    11 replies · 3 participants
  • v

    Vsevolod Kaganovych

    08/11/2020, 11:42 AM
    Guys, hi. Question: if I want to use something like PublishSubject from Rx, so I can both emit and subscribe to it, what is the analogue in coroutines? Do we still use some kind of Channel or Flow already has this functionality?
    w
    d
    +3
    12 replies · 6 participants
  • d

    Denys

    08/12/2020, 3:11 AM
    Hi all! I really need to do the following behavior. There is some source of events, for example, onСlick(), which emits items with time intervals (for example, the user clicks the button very quickly). I need to subscribe to it and collect all items with a set time interval, for example 2 sec. How can this be done with Flow API?
    o
    e
    4 replies · 3 participants
  • v

    viralshah

    08/12/2020, 4:23 PM
    I’m running a SQS Message poller in my Spring Boot App and for every message I want it to be launched on a Coroutine something like this. How should I be bridging the gap, GlobalScope? Runblocking? Is there an example of this being done
    fun processMessages(){
        for (message in messages) {
            val foo = async {processMessage(message)
            val bar = foo.await()? // Is this how we await on a suspending function?
            when (bar) {
                is Outcome.Error -> {// don't delete message, log error}
                is Outcome.Success -> {deleteMessage()}
            }
         }
    }
    
    suspend fun processMessage(message): Outcome<Foo>
    
    sealed class Outcome<out T : Any> {
    
        data class Error(val message: String, val cause: Exception? = null) : Outcome<Nothing>()
    
        data class Success<out T : Any>(val value: T) : Outcome<T>()
    }
    p
    t
    2 replies · 3 participants
  • c

    Canato

    08/12/2020, 7:35 PM
    If I open a Flow inside a Channel this will block the channel for new events? or the flow will be existing in another thread/context?
    z
    6 replies · 2 participants
  • v

    Vincent Williams

    08/13/2020, 8:11 PM
    what would you use for effects (like error message, navigation etc) instead of StateFlow? Would just a broadcast channel be used or is that going to be deprecated?
    s
    g
    20 replies · 3 participants
  • e

    eygraber

    08/13/2020, 9:02 PM
    I've been (incorrectly it seems) assuming that
    Continuation.invokeOnCancellation
    will be invoked after resuming, and I've been relying on it for internal cleanup. Is there any way to register a callback for when a continuation resumes, or do I need to handle it manually at all the resume points?
    o
    s
    8 replies · 3 participants
  • t

    turastory

    08/14/2020, 1:49 AM
    Are there any plans for supporting
    suspend operator
    soon or later? I’d like to do something like this:
    suspend inline operator fun <T> SuspendableLazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T
        = ...
    
    private val value by suspendableLazy { getValue() }
    
    fun test() = println(value)
    
    private suspend fun getValue() { ... }
    o
    5 replies · 2 participants
  • l

    Lukas Lechner

    08/14/2020, 8:09 AM
    Hi! What’s the best resource to understand error handling in coroutines? I find it very hard to grasp. Any tips for good blogposts, videos, etc?
    ➕ 2
    f
    g
    +1
    4 replies · 4 participants
  • a

    Alexander Schell

    08/14/2020, 8:15 AM
    OjWej, what have I done wrong this time? 😢
    java.lang.NoClassDefFoundError: kotlin/coroutines/AbstractCoroutineContextKey
    I thought adding kotlinx-coroutines-core to my pom.xml would be enough...? kotlin: 1.3.72 kotlinx-coroutines-core: 1.3.7 - Also tried it with 1.3.5: Same result...
    g
    10 replies · 2 participants
  • u

    ubu

    08/14/2020, 12:35 PM
    Hi guys! Having this simple custom operator (inspired by this one by Roman Elizarov):
    /**
     * Every time a new value is emitted from A, it will emit instead the latest value from B.
     */
    fun <A, B : Any> Flow<A>.switchToLatestFrom(other: Flow<B>): Flow<B> = flow {
        coroutineScope {
            val latestB = AtomicReference<B?>()
            val outerScope = this
            launch {
                try {
                    other.collect { latestB.set(it) }
                } catch (e: CancellationException) {
                    outerScope.cancel(e)
                }
            }
            collect {
                latestB.get()?.let { b -> emit(b) }
            }
        }
    }
    And verifying its behavior through some tests suite, I can’t get why sometimes (event randomly) the following test fails:
    @Test
    fun `should emit the latest value from B every time A emits something`() {
        val a = flowOf(1, 2, 3).onEach { delay(100) }
        val b =  flowOf('A', 'B', 'C', 'D').onEach { delay(25) }
    
        runBlocking {
            val result = a.switchToLatestFrom(b).toList()
            val expected = listOf('C', 'D', 'D')
    
            assertEquals(
                expected = expected,
                actual = result
            )
        }
    }
    java.lang.AssertionError:
    Expected :[C, D, D]
    Actual   :[B, D, D]
    Need help! Thanks.
    d
    j
    8 replies · 3 participants
  • v

    vineethraj49

    08/14/2020, 1:25 PM
    https://pl.kotl.in/kbrTePWXD the following runs into a deadlock(?) in kotlin 1.3.72; all the default dispatcher worker threads are in a MONITOR state 🤔 can someone point me in the direction to figuring this out?
    s
    w
    17 replies · 3 participants
  • z

    zak.taccardi

    08/14/2020, 7:09 PM
    Is there a specific version of coroutines that should be used with Kotlin
    1.4.0
    stable?
    o
    z
    +2
    8 replies · 5 participants
  • a

    Andrea Giuliano

    08/15/2020, 4:04 PM
    Hi guys, I was thinking of implementing some scatter-gather pattern for an app in Kotlin. I know Spring provides native support to it but to be hones it seems too much complex for being as simple as the scatter-gather pattern. I was thinking to use channels or maybe better flows to do so, any suggestions? Maybe there is some library ready out there?
    1 reply · 1 participant
Powered by Linen
Title
a

Andrea Giuliano

08/15/2020, 4:04 PM
Hi guys, I was thinking of implementing some scatter-gather pattern for an app in Kotlin. I know Spring provides native support to it but to be hones it seems too much complex for being as simple as the scatter-gather pattern. I was thinking to use channels or maybe better flows to do so, any suggestions? Maybe there is some library ready out there?
One idea I was thinking about would have been to emit an event (for the scatter part) where there are multiple subscribers. In the event I can pass by a Flow. then each listener will write in the flow the data it needs to. On the other side, the aggregator will use the flow sent in the event and consume it until all the listeners finished writing into that. What do you think about the approach? The only thing in my mind is that flows are sequential, which is good from the aggregator standpoint. But the scatter part should invoke the event listeners in parallel if I want them to fetch data concurrently. Do you see any problem in my reasoning?
View count: 5