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

    Devan Lai

    03/15/2022, 10:50 PM
    So I'm trying to wrap my head around interop between traditional threads and coroutines. I have a pair of reader/writer threads performing blocking operations on a serial port (using a Java library that naturally, has no concept of coroutines). I would like to execute a suspendable callback for each received message on the serial port, with some ordering guarantees (e.g, callback for message N+1 must not execute before the callback for message N has finished). Below is a toy example that demonstrates roughly what I'm doing. I have a channel that serializes the messages to be processed and a coroutine that consumes the messages in order. To actually put messages into the channel though, I launch a new coroutine just to send the message. That seems kind of weird and has me wondering if I'm overlooking something obvious.
    import kotlinx.coroutines.channels.Channel
    import kotlinx.coroutines.channels.consumeEach
    import kotlinx.coroutines.delay
    import kotlinx.coroutines.launch
    import kotlinx.coroutines.runBlocking
    import kotlin.concurrent.thread
    
    var readCount = 0
    fun blockingSerialRead(): String {
        val message = "MSG$readCount"
        readCount += 1
        // Pretend to take some time, blocking.
        Thread.sleep(500L)
        return message
    }
    
    fun main(args: Array<String>) {
        runBlocking {
            val messages = Channel<String>()
            thread(start = true) {
                while (true) {
                    val message = blockingSerialRead()
                    println("Read message $message")
                    launch {
                        messages.send(message)
                    }
                }
            }
    
            // Start a coroutine that does work on each received message
            launch {
                var takeExtraTime = false
                messages.consumeEach {
                    // Do some suspendable work with the message
                    // For example, maybe we'll send a message back
                    // and wait for the response.
                    if (takeExtraTime) {
                        // Pretend to do some expensive suspendable work
                        delay(1000L)
                        takeExtraTime = false
                    } else {
                        takeExtraTime = true
                    }
                    println("Processed message $it")
                }
            }
        }
    }
    y
    d
    • 3
    • 7
  • a

    allan.conda

    03/16/2022, 9:23 AM
    Trying to understand thread safety in coroutines… Will there be threading issues with this piece of code:
    coroutineScope {
        var count = 0
        val mutableList = mutableListOf<Int>()
        launch {
            while(isActive) {
                mutableList.add(count++)
                delay(1000)
            }
        }
        launch {
            while(isActive) {
                delay(10000)
                mutableList.take(10).also(mutableList::removeAll)
            }
        }
    }
    g
    z
    • 3
    • 6
  • m

    Michal Klimczak

    03/16/2022, 10:59 AM
    I'm trying to synchronize some calls in an okhttp authenticator and it works fine, but I'm having troubles testing it. To simplify things I reduced it to such test (in 🧵)- the important part is that
    anImportantBlockingCall
    resembles
    okhttp.Authenticator.uthenticate
    - it's a blocking call, which in my case will run a runBlocking coroutine which will synchronise a few things and wait for them. So it really is important that in this test case this remains blocking. 🧵
    • 1
    • 1
  • c

    christophsturm

    03/17/2022, 10:36 AM
    when running code with
    withTimeout
    is it possible to get a stacktrace of the thread where the timeout occurred when it occurred?
    s
    j
    • 3
    • 17
  • t

    Tower Guidev2

    03/17/2022, 10:56 AM
    Hello, i have a question regarding the use of runBlocking in production code and what is causing my intermittent failure in the following code snippet
    s
    • 2
    • 9
  • b

    Brais Gabin

    03/18/2022, 9:49 AM
    Hi! I'm trying to migrate from 1.5 to 1.6 and I have a question regarding
    UnconfinedTestDispatcher
    . Can I use
    UnconfinedTestDispatcher
    as a
    StandardTestDispatcher
    but that it does the
    advanceUntilIdle
    automatically for me? Am I missing something here? I know that I'll lose some flexibility but in a lot of my tests I don't need that flexibility.
    s
    t
    d
    • 4
    • 16
  • h

    hfhbd

    03/20/2022, 2:18 PM
    How could you create
    sharedFlow
    builder with the same signature like the cold
    flow
    builder:
    fun<T> sharedFlow(block: suspend FlowCollector<T>): SharedFlow<T>
    ? It always requires a
    CoroutineScope
    ...
    e
    o
    • 3
    • 17
  • k

    Kamila

    03/21/2022, 7:13 AM
    HI! I am fairly fresh to Kotlin and new to coroutines and flow. I am coming from Java backend so am familiar with threads and completable futures. I am wondering about one scenario, thought I ask here before doing dozens of tests myself: Given external Java API that returns
    CompletableFuture
    of different entities, for example:
    getFoo: CompletableFuture<List<FooDto>> 
    getBar: CompletableFuture<List<BarDto>>
    getWhatever: CompletableFuture<List<WhateverDto>>
    Would it be possible to use coroutines to trigger each of the call in parallel, and combine final object to be:
    Object {
        foo: List<FooDto>
        bar: List<BarDto>
        whatever: List<WhateverDto>
    }
    It is not so easy and obvious to solve with `CompletableFuture`s in Java, maybe it would be easier with
    coroutines
    ? 🤔 The point is I need to fetch multiple different entities before can calculate the final object. I can easily fetch them in sequence, but they are not dependant on each other, so should really be fetched in parallel
    r
    u
    +2
    • 5
    • 9
  • s

    Sergio C.

    03/22/2022, 5:29 PM
    Hi all, I was trying to use
    callbackFlow { }
    but the code inside the block never gets called, am I doing something wrong?
    j
    e
    g
    • 4
    • 19
  • r

    rkeazor

    03/23/2022, 4:22 AM
    hey got a question about the suspension point of channels. Given the following code snipet
    class SimpleChannelTest {
        val simpleChannel = Channel<Int>()
    
        fun simpleFunction() {
            runBlocking {
                launch {
                    simpleChannel.consumeEach { println(it) }
                }
    
                var x = 0
    
                repeat(10) {
                    simpleChannel.send(x++)
                    println("sent Message")
                }
                simpleChannel.close()
    
            }
        }
    I would expect each time send is called , the main coroutine will suspend until the data is received, however I end up with this as the result
    0
    sent Message
    sent Message
    1
    2
    sent Message
    sent Message
    3
    4
    sent Message
    sent Message
    5
    6
    sent Message
    sent Message
    7
    just wondering why this is?
    s
    n
    • 3
    • 8
  • s

    Sam Stone

    03/23/2022, 1:29 PM
    I want to become a Coroutines expert. I would like a resource (strongly prefer a book) that starts from the basics, and thoroughly goes until the very end. I found this book but it was published in July 2018, and I feel like a lot has changed, and am worried about learning out of date information. I took the tutorial on the Kotlin website, but I felt it went too fast on certain ideas, and didn't expound enough. I also learn better from many worked examples, as is common in books. I also want something more comprehensive than those tutorials. Any tips?
    m
    i
    +2
    • 5
    • 7
  • b

    bnn

    03/24/2022, 2:03 AM
    Hi, there. I am writing a network library for Android in Kotlin in which I used a lot of coroutines functionalities inside. So it’s possible to use the library from Java code, suspend functions are wrapped and hidden by callback base APIs. I found a really critical issue there. The problem happens when a user used the library with Future. If the client wrap the callback function with calling the get() method of Future in the UI thread,
    delay
    function call which is used inside the Library implementation never complete. As a result, Future.get() blocks forever. I know it’s not recommended to call Future.get() is not recommended practice. But, I would like to avoid this issue because it’s too disastrous given library clients has no idea if the
    delay
    suspend function is used under the hood. The following is the complete example code that reproduces the issue. https://gist.github.com/bananaumai/da23494ed2ba1d22c39af23a7c07ba2f#file-mainactivity-kt Any advise and/or recommendation would be appreciated. Thanks in advance.
    n
    a
    • 3
    • 10
  • p

    Paul Woitaschek

    03/24/2022, 6:36 PM
    I’m having a hard time with runTest because it makes things pass that should not pass. For example it just runs everything in sequence:
    @Test
      fun test() = runTest {
        repeat(5) {
          launch {
            println("enter")
            Thread.sleep(Random.nextLong(10))
            println("exit")
          }
        }
        println("start yield")
        yield()
      }
    Will print:
    start yield
    enter
    exit
    enter
    exit
    ...
    Is there any way to use runTest and having parallelism?
    g
    d
    +2
    • 5
    • 32
  • a

    Alexander Maryanovsky

    03/24/2022, 7:22 PM
    I’m collecting from a flow like so, as recommended:
    lifecycleScope.launch{
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
            flow.collect{
                ...
            }
        }
    }
    I would like the collection, and the entire coroutine to stop when the flow completes. But
    repeatOnLifecycle
    never returns, even after
    collect
    returns, and if the activity is stopped and restarted, collection is launched again. It seems I need
    runOnceOnLifecycle
    .
    y
    m
    • 3
    • 6
  • c

    Colton Idle

    03/25/2022, 9:15 PM
    A little bit of a discussion based around method naming. I essentially have an interface with methods like this. Not all methods have a "oneshot" and "flowable" version, but a lot of them. Some of them will be exclusively oneshot or flowable. But idk how I feel about the names. I could just have a suffix of
    Flowable
    but that smells like hungarian notiation... but I do remember a book/blog post (effective java?) that said it should be clear when a method is doing stuff with threads/async. Thoughts?
    interface MyRepository {
        suspend fun getLatestBooks(): List<Book>
        fun getLatestBooksWithLiveUpdates(): Flow<List<Book>>
        suspend fun getBookDetail(): BookDetail
        fun getBookDetailWithLivesUpdates(): Flow<BookDetail>
    }
    a
    c
    +5
    • 8
    • 23
  • t

    Thomas

    03/26/2022, 1:08 AM
    Has anyone here been able to use
    limitedParallelism
    on Kotlin/Native? When I try to use it I just get a
    ClassCastException
    . More details here: https://github.com/Kotlin/kotlinx.coroutines/issues/3223
    t
    • 2
    • 3
  • j

    janvladimirmostert

    03/26/2022, 4:59 PM
    what is the idiomatic way to implement a resources pool with Flows? let's say it's a list of numbers 1..10 that can grow and shrink resources.borrow { resource -> ... } then once a resource is done being borrowed, it is returned to the pool, if no resources are available, it waits until another borrow is completed a secondary thread can add resources or remove resources from the pool if they are no longer valid I think this is possible with Channels, but would like to use a cold flow.
    • 1
    • 1
  • b

    Brendan Campbell-hartzell

    03/28/2022, 2:10 AM
    What's the proper way to test if a flow collector received a value emitted by a sharedflow? using
    runTest
    doesn't seem to wait for a collector running in another scope to fully process the emitted value before returning. Keeping everything in the runTest scope and context just hangs the test because Flow.collect on a sharedflow never returns.
    t
    • 2
    • 8
  • u

    ursus

    03/28/2022, 10:43 PM
    how would you pause a
    timer
    type flow? it’s not really idiomatic, is it? or maybe akin to backpressure, i.e. downstream telling upstream to stop?
    r
    n
    • 3
    • 6
  • e

    Exerosis

    03/30/2022, 1:14 AM
    suspend fun debug() {
        println("${coroutineContext[STreeEvent]}")
    }
    fun main() = runBlocking {
        val test = SSubject(0)
        SComponent().apply {
            println("Component: $this")
            println("Test: $test")
            test(this, BEFORE) {
                println("${coroutineContext[STreeEvent]}")
                debug()
            }
    ...
    Can someone help me understand why :
    println("${coroutineContext[STreeEvent]}")
                debug()
    prints:
    null
    1212899836
    Why on earth would the context change between these two places?
    e
    r
    j
    • 4
    • 11
  • p

    Pablo

    03/30/2022, 11:24 PM
    One question guys! in my
    ViewModel
    I have injected a
    CoroutineDispatcher
    something like
    class FooViewModel @Inject constructor(private val dispatcher: CoroutineDispatcher){}
    Then when I'm trying to do the test I'm seeing that the test and the code in the
    ViewModel
    are working on a different thread. I know it because I've added some logs
    println("[${Thread.currentThread().name}] viewModel")
    println("[${Thread.currentThread().name}] test")
    And in the console I see :
    [Test worker] test
    [Test worker @coroutine#3] viewModel
    In the test I'm doing it as :
    private val testDispatcher = UnconfinedTestDispatcher()
    private val testCoroutineScope = TestScope(testDispatcher)
    
    @Test
    fun test() = testCoroutineScop.runTest {
     val viewModel = FooViewModel(testDispatcher)
     ...
    }
    What I'm missing?
    r
    a
    +3
    • 6
    • 40
  • k

    Kamila

    03/31/2022, 6:53 AM
    Hi guys! I am trying to learn coroutines, coming from Java background and CompletableFutures: Does this snippet make sense?
    private suspend fun fetchExternalData(futures: List<CompletableFuture<Reply>>): List<Reply> = coroutineScope {
            futures.map {
                async {
                    it.join()
                }
            }.awaitAll()
        }
    I have a list of CompletableFuture, which I would run async and do action when all of them complete. Is this the right place where I call
    join
    (or
    get()
    ) to get reply? The idea is to get a bunch of request, send them in parallel (fork) and wait for all of them (join), then combine the result
    j
    e
    • 3
    • 8
  • t

    Thomas Kranzer

    03/31/2022, 10:41 AM
    Hi, i recently updated to to newest coroutine version (1.6.0) and i am now experiencing some strange behaviour when it comes to unit testing using turbine. While the following minimal example is working fine with the now deprecated
    TestCoroutineDispatcher
    , it fails (
    TimeoutCancellationException
    ) with the new coroutines version and the
    UnconfinedTestDispatcher
    .. any ideas how this issue can be resolved?
    // ViewModel
        val loading = MutableStateFlow(false)
    
        fun onReloadClicked() {
            viewModelScope.launch {
                loading.value = true
                // load data
                loading.value = false
            }
        }
    // Test Code
        private val testDispatcher = UnconfinedTestDispatcher()    
    
        @Before
        fun setUp() {
            Dispatchers.setMain(testDispatcher)
        }    
        
        @After
        fun tearDown() {
            Dispatchers.resetMain()
        }
    
        @Test
        fun testLoading() = runTest(testDispatcher) {
            viewModel.loading.test {
                assertFalse(awaitItem())
    
                viewModel.onReloadClicked()
    
                assertTrue(awaitItem()) // fails with TimeoutCancellationException
                assertFalse(awaitItem())
            }
        }
    d
    • 2
    • 1
  • r

    Ruben Quadros

    03/31/2022, 1:20 PM
    Hi guys, I have a
    List<Flow<T>>
    what is the best way to keep collecting from each
    Flow<T>
    ?
    j
    j
    a
    • 4
    • 13
  • c

    CRamsan

    03/31/2022, 2:59 PM
    Hello everyone. I wanted to know if someone had some concrete data about the performance of Coroutines vs RxJava? I have used coroutines myself for several years and I prefer it over RxJava but I am working to migrate some codebases from Rx into coroutines and I need to convince the right stakeholders about this change. My plan was to put together a small sample program and run multiple scenarios. But if someone has some data already that they would be willing to share, that would be awesome 🙂 .
    b
    a
    • 3
    • 7
  • v

    Vladimir

    03/31/2022, 8:50 PM
    Hey guys, I’m making 4 separate DB calls sequentially, getting the results from each and returning an AggregatedResult(call1, call2, call3, call4) object with the results to the client. I’m trying to figure out how I can parallelize the DB calls and return the AggregatedResult() object once all DB 4 calls complete. Any hints as to which coroutine function to use?
    r
    j
    m
    • 4
    • 5
  • m

    mp

    04/01/2022, 9:38 AM
    hi there guys I`m working on code that should call from lock context suspend functions
    kotlin.concurrent
    
    @kotlin.internal.InlineOnly
    public inline fun <T> Lock.withLock(action: () -> T): T {
        contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) }
        lock()
        try {
            return action()
        } finally {
            unlock()
        }
    }
    but it says
    The 'checkRegistry' suspension point is inside a critical section
    Newbee with corutines\suspend so - can anyone share document reference that will help me to understand what I’ve miss
    s
    • 2
    • 2
  • c

    CLOVIS

    04/01/2022, 8:37 PM
    I'm trying to model a 'lazy suspend' task. For the moment, it's encoded as:
    val task = scope.async {
    foo()
    }
    suspend fun bar() {
    // All calls require the task to be over,
    // however only the first one(s) will really suspend,
    // since it will be ready for the others
    val foo = task.await()
    doSomething(foo)
    }
    The problem is that this requires a
    scope
    to be available when the task is instantiated. Since I do not care whether the task starts when it is instantiated or when the first call to
    bar
    is made, is there a way to adapt this pattern without requiring the
    scope
    ?
    p
    s
    g
    • 4
    • 4
  • c

    CRamsan

    04/03/2022, 3:27 AM
    Hello everyone. Some people in my team asked me for some performance numbers between coroutines and RxJava so I wrote this little app to measure performance between the two. https://github.com/CRamsan/coroutine-rx-performance I hope this is useful for people here. But the gist of what I found is that Coroutines can be a bit slower compared to Rx. But RxJava memory consumption is much higher. For me, this is another strong argument for coroutines.
    p
    m
    • 3
    • 4
  • k

    Khan

    04/04/2022, 11:51 AM
    Hello. I am trying out Kotlin flow. I have this code block but launchIn runs on main thread. How can i make it run on worker thread
    getDataUseCase().onEach { _ ->
        
    }.launchIn(viewModelScope)
    s
    • 2
    • 2
Powered by Linen
Title
k

Khan

04/04/2022, 11:51 AM
Hello. I am trying out Kotlin flow. I have this code block but launchIn runs on main thread. How can i make it run on worker thread
getDataUseCase().onEach { _ ->
    
}.launchIn(viewModelScope)
s

stojan

04/04/2022, 12:00 PM
That's because viewModelScope uses the Main dispatcher. You can switch dispatcher using flowOn
k

Khan

04/04/2022, 1:11 PM
Thanks 🙂
View count: 3