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

    Dmitry Khalanskiy [JB]

    12/17/2021, 7:25 AM
    📣 📣 📣 kotlinx.coroutines 1.6.0-RC3 is here! Mostly to fix the
    Flow.collect
    broken in RC2. Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.6.0-RC3
    🎉 4
    👍 4
    :kotlin-intensifies: 9
    👍🏼 1
    ❤️ 3
    :kotlin-intensifies-purple: 5
    l
    s
    v
    • 4
    • 7
  • t

    Tower Guidev2

    12/17/2021, 1:50 PM
    Hi, I have the following flow that im collecting to control my android activity loading state...
    j
    • 2
    • 4
  • r

    Remy Benza

    12/17/2021, 5:24 PM
    When fetching a very large contact list from an Android device (4000+) is is beneficial to run mutliple coroutines concurrently with the
    async { }
    builder? Or does the performance large depends on the I/O speed of the UFS storage?
    a
    • 2
    • 8
  • e

    Exerosis

    12/18/2021, 4:22 PM
    var resumePoint: Continuation<String>? = null
    var hasJumpedBack = false
    suspend fun test() = suspendCoroutineUninterceptedOrReturn<String> {
        resumePoint = it
        "Hello "
    }
    
    fun jumpBack() {
        if (!hasJumpedBack) {
            hasJumpedBack = true
            resumePoint?.resume("World")
        }
    }
    runBlocking {
        println("Starting")
        val result = test()
        println(result)
        jumpBack()
    }
    It had to be tested
    j
    • 2
    • 6
  • i

    igor.wojda

    12/20/2021, 7:54 AM
    Is it possible to implement repeatable task (with interval) using coroutines?
    // Run job that prints "ABC" string every 1000ms
    val repeatJob = repeatJob(1000) { println("ABC") }
    
    //until job is canceled
    repeatJob?.cancel()
    d
    • 2
    • 1
  • y

    yschimke

    12/20/2021, 9:56 AM
    Are there nice patterns in Kotlin Coroutines/Flows for having a state machine based on the inflight requests? On each request start/completion - have it evaluate whether to change some app state.
    a
    • 2
    • 3
  • p

    Pablo

    12/20/2021, 11:40 AM
    Is is possible detect when the scope is canceled in a flow
    .onCompletion
    ? I have this flow :
    flow {
      for(foo in bar downTo 0){
        emit(foo)
        delay(1_000L)
      }
    }
    Then I consume it :
    myFlow()
     .onEach {
        updateUI
      }
     .onCompletion {
       //Do something but only when the timer is 0 not when cancelled
     }
     .launchIn(scope)
    
    In some point I do cancel the scope and it automatically get into `onCompletion` so even if the timer is not over yet, it does the thing of timer finished because I have the code there, is there any way I can get if the completion is because ok the for loop or for a cancellation of scope?
    s
    p
    • 3
    • 4
  • j

    Javier

    12/20/2021, 12:28 PM

    https://www.youtube.com/watch?v=9R1IdMwSVps▾

    s
    g
    • 3
    • 3
  • a

    Alexandru Hadăr

    12/21/2021, 12:28 PM
    Could someone explained what the Key in the CoroutineContextHandler is used for? I can’t figure it out from the documentation
    m
    s
    • 3
    • 3
  • b

    brabo-hi

    12/21/2021, 9:56 PM
    Hi all, when using workmanager, how could we listen when worker is stopped within the worker ?
    n
    • 2
    • 2
  • v

    Vivek Sharma

    12/22/2021, 12:45 PM
    I am launching a coroutine like
    scope.launch{ // doing some work here which is having loops }
    I want to stop doing that work on button click so I tried doing like this:
    job = scope.launch{ // doing some work here which is having loops }
    and then canceling the job :
    job?.cancel
    but it seems like loops are executing till termination and the job is not getting canceled Any other workaround?
    t
    m
    n
    • 4
    • 5
  • v

    Vsevolod Tolstopyatov [JB]

    12/22/2021, 12:47 PM
    📣 📣 📣 kotlinx.coroutines 1.6.0 is here! • Brand new
    kotlinx-coroutines-test
    module with reworked API and multiplatform support •
    CoroutineDispatcher.limitedParallelism
    and elastic
    <http://Dispathers.IO|Dispathers.IO>
    • Out-of-the-box support of new K/N memory model •
    CopyableThreadContextElement
    for mutable context elements • And a lot of improvements and bug fixes: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.6.0 We also have a blogpost and

    what’s new▾

    video with additional details, examples and explanation
    :kotlin-intensifies: 15
    :kotlin-intensifies-purple: 8
    🎉 12
    o
    r
    +2
    • 5
    • 13
  • s

    Storozh Kateryna

    12/22/2021, 1:03 PM
    Hi all! Does anybody know if synchronized works in that way with coroutines? Could it occur any problems when I get data from map in UI thread? suspend fun loadData() { val data = getDataFromDB() data?.let { updateData(it) } } @Synchronized private fun updateData(data: Map<String, Data>) { map.clear() map.putAll(data) } @Synchronized fun getData(key: String): Data? { return map[key] }
    m
    j
    • 3
    • 12
  • m

    Maciek

    12/22/2021, 2:09 PM
    I'm having troubles understanding the exception handling in the flow. Could someone explain why the throwable completes the flow even with the 
    catch { }
     in the chain? If I'd want to have a infinite flow I must handle the exceptions with 
    try catch
     in the lambdas because flow will close after any exception "leaking" to the stream, right? Or is there a way to do some explicit recovery from the exception? Example code: only 
    0
     will be emitted, next emit 
    1
     is never executed due to flow completion after exception.
    flow {
        emit(0)
        emit(1) // never executed
    }
        .onEach { if (it == 0) throw Throwable() }
        .catch { println(it) } // catch and ignore
        .collect()
    a
    • 2
    • 8
  • u

    ursus

    12/23/2021, 3:29 AM
    I have a StateFlow<SyncState> which is written to by coroutines running on Dispatchers.IO I collect this in a ViewModel to drive UI, so the scope is driven by Dispatchers.Main I also collect this in some other place, where the scope is driven by IO Sometimes the ui driven collector doesnt receive emits (and the io collector does, so the StateFlow does actually gets written to correctly), randomly, like 1 in 10-15 I suspect this is when the writes are too close together in time? Is there a legitimate reason for all emits to be dropped in Main threaded collector due to some backpressure or something? Shouldnt I atleast see the last emit? (And yes the scope is still active, I checked) Bug?
    a
    l
    • 3
    • 5
  • g

    gotoOla

    12/23/2021, 9:59 AM
    The new limited parallelism dispatcher, does that actually limit parallelism on coroutines or is it only working in the case where you have blocking code?
    👀 1
    j
    • 2
    • 1
  • r

    rkeazor

    12/23/2021, 11:38 AM
    hey anyone have any idea how to resolve this . Seeing this when upgrading to Kotlin Coroutines 1.6.0 . i am currently using kotlin version1.6.10
    No matching variant of org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0 was found. The consumer was configured to find an API of a platform, preferably optimized for Android, as well as attribute 'com.android.build.api.attributes.BuildTypeAttr' with value 'debug', attribute 'store' with value 'googleplay', attribute 'org.jetbrains.kotlin.platform.type' with value 'androidJvm' but:
              - Variant 'commonMainMetadataElements' capability org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0:
                  - Incompatible because this component declares a usage of 'kotlin-api' of a library, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'common' and the consumer needed an API of a platform, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'androidJvm'
    l
    • 2
    • 1
  • z

    zak.taccardi

    12/23/2021, 8:18 PM
    Where is the best write-up on the
    offer(..)
    and
    trySend(..)
    change?
    d
    • 2
    • 1
  • d

    Doru N.

    12/23/2021, 9:01 PM
    Hi there. I have a question regarding Flows. How come this sample code (from docs):
    flow {
            // The WRONG way to change context for CPU-consuming code in flow builder
            withContext(Dispatchers.Default) {
                for (i in 1..3) {
                    Thread.sleep(100) // pretend we are computing it in CPU-consuming way
                    emit(i) // emit next value
                }
            }
        }
            .onEach { value -> println(value) }
            .launchIn(scope)
    crashes with java.lang.IllegalStateException: Flow invariant is violated…, but this one does not:
    flowOf(1, 2, 3)
            .transformLatest {
                withContext(Dispatchers.Default) {
                    Thread.sleep(100) // pretend we are computing it in CPU-consuming way
                    println("emitting $it, on thread: ${Thread.currentThread().name}")
                    emit(it) // emit next value
                }
            }
            .onEach {
                println("collect.onEach: $it, on thread: ${Thread.currentThread().name}")
            }
            .launchIn(scope)
    to me, it should be the same case as the first (should crash with same exception). What am I missing here? logs for 2nd sample is this:
    emitting 1, on thread: DefaultDispatcher-worker-1
    collect.onEach: 1, on thread: main
    emitting 3, on thread: DefaultDispatcher-worker-1
    collect.onEach: 3, on thread: main
    b
    • 2
    • 5
  • u

    ursus

    12/26/2021, 2:10 AM
    class Presenter {
       init {
          presenterScope.launch {
             syncer.syncingFinishedEvent
    	   .collect {
    	      navigateSomewhere()
    	   }
          }
          syncer.sync()
       }
    }
    
    class Syncer {
       fun sync() {
          syncerScope.launch {
             ...
             syncFinishedEvent.emit(Unit)
          }
       }
    }
    Is there a way to only call
    syncer.sync()
    after
    syncer.syncingFinishedEvent
    is for sure subscribed to? I cannot miss a event
    b
    n
    • 3
    • 14
  • a

    Anshulupadhyay03

    12/26/2021, 6:36 PM
    Hi Guys, I have been tyring to write a streaming client in kotlin with Flow apis. Streaming server is TCP based. I have to send request to server for subscribing / unsubscribing and listen the for the updates. I am using callback flow to keep sending the updates back to the subscribbers. Take a look at what i have implemented so far.
    private fun createConnection() {
    val hostAdd = InetAddress.getByName(endpoint)
    val connection = Socket(hostAdd, port)
    this.socketConnection = connection
    inputStream = DataInputStream(connection.inputStream)
    outPutStream = DataOutputStream(connection.outputStream)
    }
    private fun sendStreamRequest(request: String) {
    try {
    outPutStream?.writeBytes(request)
    outPutStream?.flush()
    Log.d(tag, "sendStreamRequest $request")
    } catch (ex: Exception) {
    ex.printStackTrace()
    }
    }
    The below is the methods subcribes for the updates via callback flow
    override fun subscribe(request: String):Flow<String> = callbackFlow {
    sendStreamRequest(requestFormatter.formatSubscribeRequest(request))
    try {
    inputStream?.bufferedReader().takeUnless {
    it == null
    }.use {
    it?.forEachLine { response ->
    Log.d(tag, "Streaming $response")
    val result = trySend(response)//trySendBlocking(response)
    Log.d(tag, "result  ${result.isSuccess}")
    }
    }
    } catch (ex: Exception) {
    ex.printStackTrace()
    }
    awaitClose {
    Log.d(tag, "awaitclose")
    sendStreamRequest(requestFormatter.formatUnSubscribeRequest(request))
    }
    }
    There are few problems that i see in the subscribe method 1. The whole code is written insider a singleton class so everytime i subscribe this code
    inputStream?.bufferedReader()
    will create addition objects (Let me know if i am right) 2. if i move the code `inputStream?.bufferedReader()`out of the subscribe method how can i update the subscribber ?? Can i use the produdeScope i get from callback flow builder and call trySend method from outside? 3. I also want to listen for network connection changes if the connetion looses i will establish the connection again and let the subscribber listen the updates again but not sure how to do that. Any guidance on this to improve would be of great help. I know listen streams using TCP may sound weird but it is a legacy code which i am trying to convert into Kotlin.
    n
    • 2
    • 4
  • m

    Mitchell Syer

    12/27/2021, 2:59 AM
    If I use the new
    limitedParallelism
    api like this
    <http://Dispatchers.IO|Dispatchers.IO>.limitedParallelism(1)
    , will the dispatcher always dispatch to the same thread?
    🇳🇴 2
    n
    • 2
    • 1
  • j

    juliocbcotta

    12/27/2021, 11:59 AM
    is there any operator in flow that allows me to just log an error without having to do
    catch { log(it) throw it}
    ? Something like
    doOnError
    ?
    e
    • 2
    • 2
  • p

    Pablo

    12/27/2021, 4:18 PM
    Does anyone knows if I have a custom view that extends
    ConstraintLayout
    is it good to implement the
    CoroutineScope
    ? Or it's better to create a scope
    private val scope = MainScope()
    And use it and cancel it depending on if the view is visible or not (attached/detached). The thing is that I'm doing some things and painting the custom view so I'm using a CoroutineScope for this but I'm afraid that if the CustomView is gone the coroutine is not and then try to do something and crash the app. Have anyone of you faced something similar? I used to inject the lifecycle of the "parent" let's say an
    Activity
    or a
    Fragment
    and once this is gone the coroutine is cancelled automatically.
    s
    r
    n
    • 4
    • 4
  • u

    ursus

    12/28/2021, 1:53 AM
    Technically, if I dont cancel a CoroutineScope, but all its Jobs completed, then I don't leak memory, right?
    d
    n
    +2
    • 5
    • 6
  • c

    Caio Costa

    12/29/2021, 10:09 PM
    Hello folks, I've been trying to migrate from runBlocking to runTest but to no avail. More details inside the thread. Thank you
    :thread-please: 2
    😒olved: 1
    m
    n
    +2
    • 5
    • 29
  • t

    Tim Malseed

    12/30/2021, 11:08 AM
    Hi all! I’m having trouble with a unit test. I’m trying to validate the behaviour of a StateFlow. But, the StateFlow is only in this particular state until a certain suspend function completes. During testing, my test double uses a delay to simulate a long running task. But, due to the nature of
    runBlockingTest()
    , this delay is skipped, so this function completes immediately, and the StateFlow essentially bypasses the value I’m trying to test. It’s worth mentioning, I’m using CashApp/Turbine as well.
    e
    m
    n
    • 4
    • 12
  • u

    ursus

    01/01/2022, 3:38 PM
    I'd like some advice on backpressure • Cold flows handle backpressure by default by suspending the emitter • Downstream can modify this behavior with
    buffer
    or
    conflate
    • Hot streams default behavior varies • MutableSharedFlow is suspend by default but can modify this behavior in the ctor • MutableStateFlow is conflated by default and you CANNOT modify this behavior • In both hot streams, downstream CANNOT modify this behavior (i.e. buffer or conflate dont do anything) Everything correct? (Most importantly whether downstream is able buffer on backpressure from hot upstream)
    n
    • 2
    • 15
  • t

    tseisel

    01/01/2022, 9:04 PM
    I'd like to test the following class with the new `runTest`utility:
    class SomeManager(
      private val source: DataSource,
      private val externalScope: CoroutineScope
    ) {
      private val cache: SharedFlow<Foo> by lazy {
        source.fooFlow.shareIn(externalScope, SharingStarted.EAGERLY, 1)
      }
    
      suspend fun readCached(): Foo {
        return cache.first()
      }
    }
    Why does the following test hangs forever? How can I test this kind of class that requires an external CoroutineScope ?
    @Test fun test() = runTest {
      val subject = SomeManager(someSource, this)
      val cachedValue = subject.readCached()
      assertEquals(expectedFoo, cachedValue)
      // HANGS HERE - due to having at least one child coroutine?
    }
    j
    j
    • 3
    • 5
  • n

    Nacho Ruiz Martin

    01/02/2022, 2:34 PM
    Hey! 👋 Is there any way to map values emitted by a
    StateFlow
    and still have a
    StateFlow
    and not a
    Flow
    ?
    stateflow.map(::mapper)
    returns a
    Flow
    .
    j
    s
    +3
    • 6
    • 12
Powered by Linen
Title
n

Nacho Ruiz Martin

01/02/2022, 2:34 PM
Hey! 👋 Is there any way to map values emitted by a
StateFlow
and still have a
StateFlow
and not a
Flow
?
stateflow.map(::mapper)
returns a
Flow
.
j

Joffrey

01/02/2022, 2:36 PM
To have another
StateFlow
you would need to store a new state and to have a coroutine that collects the source flow into the new one. You could use stateIn after
map
to do that for you behind the scenes.
n

Nacho Ruiz Martin

01/02/2022, 2:37 PM
😞 Ok, sounds a bit weird coming from Rx, but looks doable. Thanks!
j

Joffrey

01/02/2022, 2:37 PM
What would you do in Rx? Also, why do you need a
StateFlow
as a result there (why is
Flow
not sufficient)?
n

Nacho Ruiz Martin

01/02/2022, 2:41 PM
I need a
StateFlow
just to have better integration with Jetpack Compose. In
Rx
a simple
map
on a
BehaviourSubject
would suffice, if I’m not mistaken.
s

streetsofboston

01/02/2022, 2:49 PM
The return type of the
map
method on
BehaviorSubject
is a plain
Observable
(which is comparable to a plain
Flow
), which gives you the same type of problem that you are asking about. http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/subjects/BehaviorSubject.html
n

Nacho Ruiz Martin

01/02/2022, 2:49 PM
🤔 You’re absolutely right.
m

Martin Rajniak

01/02/2022, 2:58 PM
@Nacho Ruiz Martin FYI, you don't need StateFlow in JetpackCompose You can collect Flow as state as well https://developer.android.com/reference/kotlin/androidx/compose/runtime/package-summary#(kotlinx.coroutines.flow.Flow).collectAsState(kotlin.Any,kotlin.coroutines.CoroutineContext)
🙇 1
a

Adam Powell

01/02/2022, 4:18 PM
You can, but you need to supply your own initial value since the collection doesn't begin until initial composition has completed
➕ 3
Most of the time when people ask for this is because they are using StateFlow for hot state instead of snapshots, and snapshots can do this natively https://github.com/Kotlin/kotlinx.coroutines/issues/2631#issuecomment-859662590
🤔 1
(example in the linked comment)
n

Nacho Ruiz Martin

01/02/2022, 5:50 PM
Yes, that’s exactly my case, Adam. I ended up re-casting my Flow to StateFlow with
stateIn
. Feels a bit weird, but it works.
h

hfhbd

01/02/2022, 10:51 PM
Although compose
(Mutable) State
is nice, the advantage using
StateFlow
is multiplatform support, especially iOS.
View count: 6