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

    Kris Wong

    02/05/2021, 4:37 PM
    when calling a 
    suspend
     function within 
    runBlocking
     , the following code should not be executed until the function completes, correct? I am seeing some flakiness in a test that doesn't make sense to me.
    ✔️ 1
    w
    l
    +1
    47 replies · 4 participants
  • j

    Jason Ankers

    02/05/2021, 4:43 PM
    launch {
        val result = getSomething().apply {
            doSomethingSuspending()
        }
        // code at this point never runs
    }
    Could anyone explain why this happens?
    w
    g
    +1
    23 replies · 4 participants
  • g

    Gilles Barbier

    02/05/2021, 7:56 PM
    Hi, I'm using a
    MutableSharedFlow
    with a collect lambda.
    val responseFlow = MutableSharedFlow<Message>(replay = 0)
    ...
    responseFlow.collect {
    ...
    }
    When I collect a message, I do a test and for some value , I would like to leave the collect function and return a value. I'm not sure how to do that. Any idea?
    w
    3 replies · 2 participants
  • g

    Gilles Barbier

    02/05/2021, 9:48 PM
    Hi, I'm calling a proxy from a suspend function
    suspend fun test() {
      o.method()
    }
    here,
    o
    is a proxy obtained by
    Proxy.newProxyInstance(..., proxyHandler)
    . So this will call the
    invoke
    method of
    proxyHandler
    . My question is: how can I propagate the suspend up to
    proxyHandler
    and use a suspend function from its
    handle
    method (without having to start a runBlocking of course) ?
    j
    4 replies · 2 participants
  • f

    Florian

    02/06/2021, 12:21 PM
    If I call
    delay
    or any other blocking operation inside the
    collect
    block of a Flow, the next value will not be collected until that delay is over right? So I can't get race conditions between successive emissions of the Flow?
    d
    p
    +1
    6 replies · 4 participants
  • b

    Brais Gabin

    02/06/2021, 12:34 PM
    Is there a way to do a cartesian product of two flows? Something similar to
    join
    in RxJava? I have a flow of files and a flow of processors and I need to run all the processors through all the files. I'm looking for something like:
    filesFlow.join(processorsFlow) { file, processor -> processor.invoke(file) }
    (
    proccessor.invoke
    returns the result of the processor so I get new flow of type result)
    d
    e
    +1
    8 replies · 4 participants
  • g

    Gilles Barbier

    02/06/2021, 10:39 PM
    Hi, I do not understand the following behavior:
    fun main() {
        val flow = MutableSharedFlow<Int>(replay = 0)
    
        runBlocking {
            launch {
                println( flow.first { it >= 90 } )
            }
    
            launch(<http://Dispatchers.IO|Dispatchers.IO>) {
                repeat(1000) {
                    flow.emit(Random.nextInt(0, 100))
                }
            }
        }
    }
    This code does not print anything. It prints when I remove
    <http://Dispatchers.IO|Dispatchers.IO>
    at the second launch or (sometimes) if I add
    <http://Dispatchers.IO|Dispatchers.IO>
    at the first launch... any explanation?
    z
    4 replies · 2 participants
  • f

    Florian

    02/07/2021, 1:35 AM
    What should I use instead of
    MutableStateFlow
    as my
    flatMapLatest
    trigger when I need to allow emitting the same value in succession? Channel?
    l
    2 replies · 2 participants
  • r

    Remy Benza

    02/07/2021, 10:05 AM
    I'm sorting a large list (10.000+) items with use of the
    <http://Dispatcher.IO|Dispatcher.IO>
    from an Android room database. What pattern is recommended to use?
    d
    j
    +1
    17 replies · 4 participants
  • j

    jean

    02/08/2021, 10:22 AM
    private val supervisor = SupervisorJob()
    private val coroutineScope = CoroutineScope(coroutineContext + supervisor)
    ...
    fun onEvent(event: MyEvent) {
        coroutineScope.launch {
            val data = findHeavyWorkToExecute()?.invoke()
                ?: throw Exception(currentState, event)
    
            someMoreWork(data)
         }
    }
    I’m want
    someMoreWork()
    to be executed only if the lambda returned by
    findHeavyWorkToExecute()
    is not null and its execution does not fail. But when I test this
    someMoreWork()
    is called even though the
    throw
    statement occurs. What am I suppose to change there?
    w
    4 replies · 2 participants
  • j

    james

    02/08/2021, 12:02 PM
    I wasn't sure wether to post here or in #android, but the issue I'm having is with the Kotlin coroutines library. Just need some help getting my head around what I'm doing wrong!
    # MainActivity.kt
    
    override fun onStart() {
            super.onStart()
            var applicationID = runBlocking { Application.registerDevice() }
    
            Log.d("AppID on-start", applicationID)
        }
    # Application.kt
    
    object Application {
        suspend fun registerDevice(): String {
            return getTokenAsync().await()
        }
    
        private suspend fun getTokenAsync(): kotlinx.coroutines.Deferred<String> = coroutineScope {
            async {
                return@async FirebaseInstallations.getInstance().id.result.toString()
            }
        }
    }
    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.application, PID: 20890
        java.lang.IllegalStateException: Task is not yet complete
    If anyone could see where I'm going wrong and help point me in the right direction on what I can do to resolve this I would really appreciate it 🙂 Thanks in advance!
    a
    a
    9 replies · 3 participants
  • n

    Niklas Gürtler

    02/08/2021, 12:02 PM
    When I catch a
    CancelledException
    from a Coroutine, can I find out where the cancel originated from? Some of my coroutines are spuriously cancelled and I'm trying to find out why 🤔
    g
    4 replies · 2 participants
  • v

    Vivek Sharma

    02/08/2021, 1:32 PM
    while using flow.first() operator, it throws exception when flow is empty as docs say, but I am fetching list from database using a flow and checking if that flow.first() , and if the list is empty , does it mean flow is empty ?
    w
    g
    9 replies · 3 participants
  • n

    natario1

    02/08/2021, 2:23 PM
    Given this class
    class Client {
    
        private suspend fun connectInternal(url: String) { /* does connection stuff */ }
        private suspend fun disconnectInternal() { /* does disconnection stuff */ }
    
        suspend fun connect(url: String) {
            TODO("Should call connectInternal")
        }
    
        suspend fun disconnect() {
            TODO("Should call disconnectInternal")
        }
    }
    I'd like to implement
    connect
    and
    disconnect
    so that they call the internal APIs in a thread-safe fashion. Client can only be connected to one url at a time so, for example: • disconnect should cancel any in-progress connection • when connect is called from multiple threads, only the last succeeds, the others will be canceled I can implement this in a thousand ways, but I always end up using some Java threading primitive at least in 1 place (like a synchronized block or a lock). Is there a way to achieve the same only with coroutine primitives? One simple option is do everything in like a
    newSingleThreadContext
    but that's more of a bad workaround
    s
    v
    +2
    7 replies · 5 participants
  • t

    taer

    02/08/2021, 8:19 PM
    Is this ok to do?
    val pool = Executors.newFixedThreadPool(N)
    val dispatcher1 = pool.asCoroutineDispatcher()
    val dispatcher2 = pool.asCoroutineDispatcher()
    👎 2
    🇳🇴 1
    z
    8 replies · 2 participants
  • p

    pablisco

    02/08/2021, 10:45 PM
    Has anyone experienced this? (Kotlin: 1.4.21, Coroutines: 1.4.2, AS: 4.2 Canary 16) I’ve already wasted hours on this. The interesting thing is that the code runs ok 🤔
    g
    4 replies · 2 participants
  • v

    Vivek Sharma

    02/09/2021, 10:05 AM
    I have like
    2 flows
    and I want to observe their changes with
    flatMapLatest
    , if either of them emit new value, I want to trigger some action, but how can I observe on
    2 flows
    , should I combine them ? how can I do so
    w
    g
    +1
    7 replies · 4 participants
  • e

    efemoney

    02/09/2021, 11:01 AM
    Do I need to explictly
    close
    a channel if I only want to
    receive
    a single value from it? Something like this inside some suspend function
    val whatIWant = myChannel.receive()
    myChannel.close()
    return whatIWant
    
    // VS
    
    return mychannel.receive()
    v
    m
    12 replies · 3 participants
  • w

    william

    02/10/2021, 1:15 AM
    is there an operator to plumb the output of one flow as the input to another (sharedflow)
    z
    6 replies · 2 participants
  • c

    Colton Idle

    02/10/2021, 2:25 AM
    Why is it when I try to use
    MaterialTheme.colors.*
    I get an error of "@Composable invocations can only happen from the context of...", but if I just use a string there instead then it works fine, which shows that my @Composable is actually setup correctly. Code snipipets in thread.
    r
    a
    13 replies · 3 participants
  • n

    natario1

    02/10/2021, 11:17 AM
    Trying to cancel flow emission when a certain scope (not the collector scope) dies. I thought
    flowOn
    would help but the scope there can't have a Job, which makes sense in the end. So I'm thinking of
    flow.onEach { myScope.ensureActive() }
    Is this the only way to do it? Are there any concerns other than performance?
    v
    2 replies · 2 participants
  • s

    Slackbot

    02/11/2021, 7:43 AM
    This message was deleted.
    a
    1 reply · 2 participants
  • j

    jean

    02/11/2021, 7:56 AM
    Is there a specific method I should use on a
    Channel
    to cast it to a type allowing me only to send/offer? The same way there is
    receiveAsFlow
    to only be able to collect it, how can I restrict my code to only sending?
    a
    2 replies · 2 participants
  • a

    appasni

    02/11/2021, 1:59 PM
    fun main(): Unit = runBlocking {
        println(1)
        launch {
            println(2)
            launch {
                println(3)
            }
        }
        launch {
            println(4)
        }
        println(5)
    }
    why does the above code print 1 5 2 4 3 instead of 1 2 3 4 5 everything is running in main thread?
    n
    w
    +3
    20 replies · 6 participants
  • m

    Mohamed

    02/11/2021, 4:10 PM
    How to use
    withTimeout
    inside
    suspendCoroutine
    ? something like:
    suspendCoroutine{ cont->
      withTimeout(1000){
        // DO something
        cont.resumeWithException(Exception("Timeout"))
      }
    }
    g
    z
    +2
    18 replies · 5 participants
  • k

    Kshitij Patil

    02/12/2021, 9:07 AM
    How to catch all the exceptions possibly thrown by multiple jobs launched in same scope (SupevisorScope)? Currently I’m doing something like this but no exceptions are getting caught
    SupervisorscopeExceptions
    e
    12 replies · 2 participants
  • l

    Lena Stepanova

    02/12/2021, 10:40 AM
    Hi, is there a way to pass @launch to another function? I have this piece
    viewModelScope.launch { 
        validateEmail(user)?.let {
            _errorLiveData.postValue(it)
            stopLoading()
            return@launch
        }
    }
    And I want it to look something like
    evaluate(validateEmail(user), launch)
    with
    fun evaluate(result: String?, job: (
        context: CoroutineContext,
        start: CoroutineStart,
        block: suspend CoroutineScope.() -> Unit
    ) -> Job){
        result?.let {
            _errorLiveData.postValue(it)
            stopLoading()
            return@job
        }
    }
    I get job is unresolved, so what am I doing wrong and how to make it right?
    w
    m
    18 replies · 3 participants
  • n

    Niklas Gürtler

    02/12/2021, 3:42 PM
    Would this be a good pattern for a function that both fetches one single data element, and also a series of other data elements simultaneously?
    fun fetchData (scope : CoroutineScope) : Pair<Deferred<Int>, Channel<Float>> {
        // Start first operation
        val r1 : Deferred<Int> = scope.async {
            delay (200) // Pretend to do some work
            42  // Return a result
        }
    
        val r2 = Channel<Float> ()
    
        // Start second operation
        scope.launch {
            repeat (10) {
                delay (it * 100L) // Pretend to do some work
                r2.send(it.toFloat()) // Return one result
            }
            // Second operation done
            r2.close()
        }
    
        return Pair(r1, r2)
    }
    
    
    fun main () {
        val results = fetchData(GlobalScope)
    
        runBlocking {
            launch {
                val res1 = results.first.await()
                println("Result 1 : $res1")
            }
            launch {
                for (elem in results.second) {
                    println ("Result 2 elem: $elem")
                }
            }
        }
    }
    Without coroutines, I'd use a callback interface with functions
    onResult1(x:Int)
    and
    onResult2(x : Float)
    and call the first one once and the second one multiple times.
    w
    4 replies · 2 participants
  • n

    natario1

    02/12/2021, 4:49 PM
    Is there any operator for
    Flow<Flow<T>>
    like
    flatten*
    which can cancel child flow collection when a new parent value is emitted? Say you have
    fun parentFlow(): Flow<String> = ...
    fun childFlow(id: String): Flow<Result> = ... // id comes from parentFlow
    My goal is to have a single
    Flow<Result>
    , taking the id from parent flow. One way to do this is:
    val merged: Flow<Flow<Result>> = parentFlow().map { childFlow(it) }
    val flat: Flow<Result> = merged.flattenConcat()
    However in my case the parent id represents a kind of state, so when a new id is emitted, the flow should stop collecting the previous
    childFlow
    . I'm struggling to find an elegant way to do this. I could collect the child inside the parent body (inside
    flow { }
    for example), but then not sure how to cancel the previous one
    w
    o
    3 replies · 3 participants
  • s

    spierce7

    02/13/2021, 12:07 AM
    MutableStateFlow
    emits the last known value when it’s collection is started, and it also doesn’t publish a value if it
    equals
    the previous event. If I wanted something that just receives events as they come in, and also publishes EVERY event regardless of whether it’s the exact same event as the last one, what are my options?
    j
    i
    4 replies · 3 participants
Powered by Linen
Title
s

spierce7

02/13/2021, 12:07 AM
MutableStateFlow
emits the last known value when it’s collection is started, and it also doesn’t publish a value if it
equals
the previous event. If I wanted something that just receives events as they come in, and also publishes EVERY event regardless of whether it’s the exact same event as the last one, what are my options?
j

Javier

02/13/2021, 12:08 AM
SharedFlow
s

spierce7

02/13/2021, 12:16 AM
Thank you. Looks promising. I forgot about these 🙂
i

Ian Lake

02/13/2021, 1:09 AM
The canonical article about this is https://elizarov.medium.com/shared-flows-broadcast-channels-899b675e805c which has a lot of use cases and what is appropriate for each
s

spierce7

02/13/2021, 2:24 AM
thanks 🙂
View count: 4