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

    octylFractal

    11/10/2020, 5:13 AM
    is there a flow equivalent to http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/core/Observable.html#buffer-long-java.util.concurrent.TimeUnit-int- ?
    g
    d
    +1
    8 replies · 4 participants
  • d

    dephinera

    11/10/2020, 7:48 AM
    Hello, What would be the proper pattern to await multiple coroutines with different results? Is there an alternative to awaitAll? I don't like the necessary casting... I was thinking of using joinAll(...) and then
    deferred.getCompleted()
    , but
    getCompleted()
    is experimental.
    viewModelScope.launch(Dispatchers.MAIN) {
        val deferred1 = async { operation1() }
        val deferred2 = async { operation2() }
        val deferred3 = async { operation3() }
        val deferred4 = async { operation4() }
    
        val results = awaitAll(deferred1, deferred2, deferred3, deferred4)
        
        val res1 = results[0] as? Type1
        val res2 = results[1] as? Type2
        val res3 = results[2] as? Type3
        val res4 = results[3] as? Type4
    }
    e
    2 replies · 2 participants
  • l

    Larten

    11/10/2020, 9:18 AM
    Hi all! I have a flow, which emits on database change. The query has a date parameter (today) which filters in the query on the data side. I have to detect the midnight and update the query to show correct data. Is there any good solutions to this?
    b
    2 replies · 2 participants
  • s

    spand

    11/10/2020, 10:15 AM
    Can I mark my methods as blocking to opt-in to the "inappropriate blocking call" warning somehow?
    b
    l
    +1
    15 replies · 4 participants
  • f

    Florian

    11/10/2020, 6:04 PM
    Are there any benefits LiveData still has over Flow? Or can Flow do anything LiveData can do?
    👍 1
    c
    i
    +9
    65 replies · 12 participants
  • r

    rkeazor

    11/10/2020, 9:29 PM
    if sharedFlow.tryEmit, returns false those that mean the value will not be emitted ?
    e
    1 reply · 2 participants
  • t

    Tim Malseed

    11/11/2020, 6:41 AM
    I'm trying to track down the source of a
    JobCancellationException
    . My crash reporting tool isn't offering any useful information, and I don't quite understand this exception..
    e
    l
    11 replies · 3 participants
  • m

    Mark McCormick

    11/11/2020, 9:51 AM
    Hello everybody ✋ Im struggling to find a way how to to deal with order of my coroutines. I have a dashboard with multiple items. After I load the items I load additional info for each item on the dashboard. Meanwhile I can click any item on the dashboard to show item’s detail. Currently the detail starts to load only after all the additional info on the dashboard is loaded, which is something I would like to change. Ideally, I would like to start loading detail info before dashboard is finished. It is an android app and Im using
    witchContext(<http://Dispatchers.IO|Dispatchers.IO>)
    for all the rest api calls. Do you have any suggestions? Thank you :)
    f
    3 replies · 2 participants
  • b

    bobby

    11/11/2020, 10:17 AM
    Hi All, I had a code looks like below
    fun main() {
        viewModelScope.launch {
            doA()
            //call api with Flow as the return type
        }
    }
    
    suspend fun doA() {
        viewModelScope.async { doB() }.await()
    }
    
    suspend fun doB() {
        //Do logic here, eventually will call line below
        viewModelScope.launch { doC() }
    }
    
    suspend fun doC() {
        //call api with Flow as the return type
    }
    What I want to achieve from the code above is to wait for the
    doA()
    function to finished and then continue to call the API, but when I tried to run the code, the
    doA()
    is executed first but it continue to call the API rather than waiting for the
    doA()
    to finish. Is there's something wrong with the code? Yes, the code is quite bad, I still kind a new with the Coroutine, thanks for helping, really appreciate it
    n
    7 replies · 2 participants
  • a

    ariedov

    11/11/2020, 12:42 PM
    Hey! I have a weird question. I have a list of object and have to make a network call for every object, but they have to be made once a 10 seconds, and not faster. I was thinking, maybe I could somehow create a separate coroutine scope for each object and call a
    delay
    inside each call inside the
    scope.launch
    . Any suggestions would be very welcome, thank you!
    j
    g
    6 replies · 3 participants
  • e

    Evgeniy Zaharov

    11/11/2020, 2:06 PM
    Hi, I have a problem with switching from ReactorContext to CoroutineContext In coroutine-reactor docs I found an example:
    val flow = flow<Unit> {
       println("Reactor context in Flow: " + coroutineContext[ReactorContext])
    }
    
    flow.asFlux()
        .subscriberContext { ctx -> ctx.put("answer", 42) }
        .subscribe() // Must print "Reactor context in Flow: Context{'answer'=42}" but print "Reactor context in Flow: null"
    But with coroutine 1.4.0, 1.4.1 it prints Null. Am I miss something?
    1 reply · 1 participant
  • b

    Bruno Ortiz

    11/11/2020, 7:08 PM
    Is the a way to resume a flow on error?
    fun main() = runBlocking<Unit> {
        emit()
            .onEach {
                if (it == 5) error("oof! some random error occurred.")
                println(it)
            }.catch { println("some error occurred") }
            .collect()
    }
    
    
    fun emit() = flow {
        for (i in 1..10) {
            emit(i)
        }
    }
    This will print "1 2 3 4" and stop. I'd like to print every number except number 5. (I'm doing this to simulate a random error, i know that in this specific case i could filter out the number 5).
    a
    s
    7 replies · 3 participants
  • n

    napperley

    11/11/2020, 11:46 PM
    Are there instructions available on building/publishing the KotlinX Coroutines library for the linuxArm32Hfp and linuxArm64 targets?
    👍 2
    2 replies · 1 participant
  • t

    Tolriq

    11/12/2020, 9:08 AM
    Was wondering if there some more idiomatic ways to accomplish :
    fun scheduleRefresh() {
    	job?.cancel()
    	job = launch {
    		while (isActive) {
    			val newRefreshTime = getARefreshTime()
    			if (newRefreshTime == 0) {
    				break
    			}
    			delay(newRefreshTime)
    			doSomething()
    		}
    	}
    }
    g
    n
    +1
    5 replies · 4 participants
  • n

    Nikky

    11/12/2020, 4:25 PM
    how can i retrieve MDC from a CoroutineContext in a exception handler ?  the code looks like so currently
    private val exceptionHandler = CoroutineExceptionHandler { context, e -> GlobalScope.launch(MDCContext() + context) {
    can i somehow do 
    context.getCopyOfContextMap()
      ?
    l
    g
    +1
    7 replies · 4 participants
  • r

    rkeazor

    11/13/2020, 5:10 AM
    hey in the documentation SharedFlow.flowOn(...) has no affect if I understand it correctly . So how do you switch dispatchers when collecting from the shared Flow?
    l
    z
    7 replies · 3 participants
  • m

    Michal Klimczak

    11/13/2020, 7:26 AM
    Hi guys, I'm trying to add unit tests to the StateFlow and it's awfully unpredictable (to me). Can you explain to me based on this example (the test passes like this):
    @Test
        fun `stateIn self-contained example`() = runBlockingTest {
    
            suspend fun makeHeavyRequest(): String {
                return "heavy result"
            }
    
            val flow = flow<Unit> {} //in production this is a channel meant to refresh the Flow
                .onStart { emit(Unit) }
                .map { makeHeavyRequest() } //using mapLatest breaks 
                .flowOn(testDispatcher)
    //            .onEach {  } //uncommenting this line also breaks
                .stateIn(GlobalScope, SharingStarted.WhileSubscribed(), "init state")
    
            val results = mutableListOf<String>()
            val job = launch {
                flow.collect { results.add(it) }
            }
    
            assertEquals("heavy result", results[0])
    
            job.cancel()
    
        }
    1. Why the test breaks (I get
    init state
    instead of
    heavy result
    ) when I use
    mapLatest
    instead of
    map
    ? 2. Why the test breaks (I get
    init state
    instead of
    heavy result
    ) when I uncomment the
    onEach
    below the
    flowOn
    ? 3. Bonus question: why don't I get both, the
    init state
    AND the
    heavy result
    ?
    a
    s
    9 replies · 3 participants
  • f

    FunkyMuse

    11/13/2020, 10:39 AM
    Hello folks, is there any way to transform flow into state flow like an extension function or something else?
    b
    2 replies · 2 participants
  • n

    Nikky

    11/13/2020, 12:03 PM
    another questions about MDC and coroutineContext.. can i update a ThreadContextElement from inside the coroutine ? issue is this code seems natural
    suspend fun doStuff() = withContext(MDCContext() + exceptionHandler()) {
       MDC.put("flow", "do-stuff")
       <http://logger.info|logger.info> { "doing stuff" } // mdc is fine here
    
       someSuspendFun()
    
       <http://logger.info|logger.info> { "done doing stuff" } // mdc was reset to the state of MDCContext ie. is empty
    }
    ideally what i would like to be able to do is update the MDCContext or update the
    val contextMap: MDCContextMap
    after i modify the MDC ( i tried, it fails in different ways ) or use a mechanism where the MDC is stored before doing a suspend call, so any changes are actually picked up TL;DR currently it leads to rather unnatural looking code and additional nesting or errors that are really hard to find
    g
    b
    6 replies · 3 participants
  • u

    ubu

    11/14/2020, 11:58 AM
    Hello there! Is there a way to check if a
    Flow<T>
    with
    debounce(...)
    operator applied to it has currently a pending value that will be emitted after debounce delay? I have a specific problem with the following use case on Android. Inside a
    ViewModel
    , I am using a
    Channel<String>
    to organize pipeline for sending text changes to some remote backend: this channel is consumed as
    Flow<String>
    , where on each emission the value is sent (with delay resulting from
    debounce()
    operator) to the backend. When this
    ViewModel
    is to be destroyed and
    onCleared()
    is called, I cancel that same
    Channel<String>
    . But there is an expected but still unpleasant side-effect, which I need to eliminate: the last value is not guaranteed to be sent if there is a pending emission due to debounce delay, which gets cancelled when
    channel.cancel()
    is called. Any suggestions will be very appreciated!
    b
    1 reply · 2 participants
  • a

    Ananiya

    11/14/2020, 4:42 PM
    is kotlin.coroutines diprycted yet, why i am asking this is kotlinx.coroutines are used rather than kotlin.coroutines(from standard-lib)
    e
    g
    4 replies · 3 participants
  • a

    Archie

    11/14/2020, 6:45 PM
    Hi Everyone, Please help. I was trying to do:
    2sec     2sec     2sec
    ------[A]------[B]------[C]------...----------------> InitailFlow
           \        |        | 
            \      drop      drop
             \
         5sec \    5sec        5sec
    ----------[1]---------[2]---------[3]-----|> AnotherFlow
    
    result: [A1, A2, A3]
    So I have
    InitailFlow
    which emits a short amount of time (2 seconds) which is then transformed to
    AnotherFlow
    which takes longer to finish (15 seconds in total)... I would like to drop the other incoming items emitted by the
    InitialFlow
    while
    AnotherFlow
    isn't finished... I've tried:
    flow{
        delay(2000)
        emit("A")
        delay(2000)
        emit("B")
        delay(2000)
        emit("C")
    }.buffer(0, BufferOverflow.DROP_LATEST)
        .onEach {
           println("Event for $it")
        }
        .flatMapConcat {
           flow {
               delay(5000)
               emit("${it}1")
               delay(5000)
               emit("${it}2")
               delay(5000)
               emit("${it}3")
            }
         }
         .onEach {
             println(it)
         }
         .launchIn(scope)
    But for some reason this is the result:
    Event for A
    A1
    A2
    A3
    Event for B
    B1
    B2
    B3
    It still process Event B for some reason even when I have a
    .buffer(0, BufferOverflow.DROP_LATEST)
    . Why does it still process Event B? Is there a way to do this? Thanks in advance.
    h
    m
    +1
    18 replies · 4 participants
  • f

    Florian

    11/15/2020, 9:32 AM
    if I use
    runBlockingTest
    , will it execute coroutines launched within it sequentially? (as if I called
    join
    on them)
    a
    g
    4 replies · 3 participants
  • s

    Simon Lin

    11/16/2020, 5:42 AM
    What is the alternative using flow or channel for SingleLiveEvent in this situation:
    val onSuccess = SingleLiveEvent<Unit>()
    
    fun load() {
        // do something
        onSuccess.call()
    }
    a
    t
    +2
    4 replies · 5 participants
  • d

    diesieben07

    11/16/2020, 10:58 AM
    How do I properly clean up resources when using
    flow
    ? For example if I open an IO Stream in the
    flow {}
    builder, how do I clean it up? I can't use
    onCompletion
    , because I don't have the stream available there obviously. If I understand the docs correctly I am not supposed to use
    try-finally
    in the
    flow {}
    builder, correct?
    ✅ 1
    f
    3 replies · 2 participants
  • e

    Egor Egorov

    11/17/2020, 5:21 AM
    Hey Kotlin Community! I am trying to write end to end testing where entry point is Android
    ViewModel
    and last point is
    MockWebServer
    from OkHTTP using
    Coroutines
    . In ViewModel I make a call using
    viewModelScope.launch
    . However when I try to run this code
    @get:Rule
        var instantExecutorRule = InstantTaskExecutorRule()
    
        @get:Rule
        var mainCoroutineRule = MainCoroutineRule()
    
        @Test
        fun reloadExpense() = runBlocking {
            viewModel.reloadExpense()
            assertThat(viewModel.state.value, CoreMatchers.instanceOf(LCE.Content::class.java))
        }
    It does not wait for API request and just finishes the test. The MainCoroutine Rule is
    @ExperimentalCoroutinesApi
    class MainCoroutineRule : TestWatcher(), TestCoroutineScope by TestCoroutineScope() {
    
        override fun starting(description: Description?) {
            super.starting(description)
            Dispatchers.setMain(this.coroutineContext[ContinuationInterceptor] as CoroutineDispatcher)
        }
    
        override fun finished(description: Description?) {
            super.finished(description)
            Dispatchers.resetMain()
        }
    }
    I have tried using
    runBlockingTest
    ,
    runBlocking
    and different types of rules. Nothing seems to work. Thank you in advance!
    m
    r
    5 replies · 3 participants
  • j

    John O'Reilly

    11/17/2020, 11:03 AM
    When is it hoped that there'll be
    1.4.1-native-mt
    version of Kotlinx Coroutines available?
    ➕ 6
    e
    2 replies · 2 participants
  • a

    Andrea Giuliano

    11/17/2020, 11:59 AM
    Hi folks, I’m working with coroutines and I’ve a question about how to implement a coroutine factory. My use case: I’m implementing an interface 
    MetricEmitter
     where consumers can simply call 
    emitMetric(observation)
     . Under the hood this 
    MetricEmitter
     will spin up an actor responsible for ingesting those metric observations. From the external consumer of this 
    MetricEmitter
     I just want to expose methods such as: • `metricEmitter.initialize()`: which will spin up the actor and ticker • `metricEmitter.emitMetric()`: which will ingest the observation • `metricEmitter.close()`: which will flush remaining metrics and tear down the actor My problem is that in the 
    initialize()
     function, when I try creating the actor, it requires me to provide a 
    CoroutineScope
    . If I use 
    coroutineScope { actor<Msg>{... }
     this code block will freeze the whole execution since it will complete when the actor terminates. That’s not what I want. I’ve managed to solve the issue by passing a coroutineScope as argument of 
    metricEmitter.initialize(scope: CoroutineScope)
     but not sure if this is a smell/antipattern. Any idea how to solve/remodel the solution?
    z
    t
    4 replies · 3 participants
  • e

    Evgeniy Zaharov

    11/17/2020, 12:47 PM
    Hi. Does anybody know why mutex is much slowly compared to synchonization? In thread I will add small example:
    t
    6 replies · 2 participants
  • t

    Tolriq

    11/17/2020, 1:14 PM
    Can someone explain the difference between
    asSharedFlow()
    on a
    MutableSharedFlow
    vs just exposing the
    MutableSharedFlow
    as a
    SharedFlow
    ?
    w
    3 replies · 2 participants
Powered by Linen
Title
t

Tolriq

11/17/2020, 1:14 PM
Can someone explain the difference between
asSharedFlow()
on a
MutableSharedFlow
vs just exposing the
MutableSharedFlow
as a
SharedFlow
?
w

wasyl

11/17/2020, 1:25 PM
If you expose
MutableSharedFlow
as
SharedFlow
then someone could still cast it back to
Mutable..
and send values to it.
asSharedFlow
fully hides the underlying mutable shared flow from consumers
👍 3
t

Tolriq

11/17/2020, 1:31 PM
Thanks, so exposing as SharedFlow for something that is 100% internal is not an error, it's just better habit to use the other one to avoid future possible troubles.
w

wasyl

11/17/2020, 1:35 PM
Yep both will behave the same, just using
asSharedFlow
is imo good practice. Even if you don’t develop a library, it’s still good to make it impossible to make a mistake by fellow devs — I can imagine someone doing
if (someFlow is MutableSharedFlow) someFlow.castAndSend(x)
with good intentions
👍 2
View count: 4