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

    oday

    11/15/2022, 12:32 PM
    is this not how I would observe the changes in these MutableStateFlows?
    private val categoryFilter = BrowseEventsFilter.CategoryFilter(category = MutableStateFlow(Category.All))
    private val locationFilter = BrowseEventsFilter.LocationFilter(location = MutableStateFlow(null))
    private val periodFilter = BrowseEventsFilter.PeriodFilter(
        period = MutableStateFlow(Period.Any),
        dateRange = MutableStateFlow(null)
    )
    and then you change them
    var filtersState = MutableStateFlow(listOf(locationFilter, periodFilter, categoryFilter)) // collectAsState in the activity
    
    // how they change
    filterState?.enabled?.value = ChipStatus.ENABLED
    filterState?.period?.value = period
    filterState?.dateRange?.value = null
    and then observe them
    flowOf(periodFilter.period?.value,
        periodFilter.dateRange?.value,
        categoryFilter.category.value,
        locationFilter.location.value
    ).collect {
    
    // do something everytime their values change
    }
    b
    • 2
    • 2
  • c

    czuckie

    11/16/2022, 9:44 AM
    I've found https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-delay-controller/pause-dispatcher.html which promises to fix all my problems and fulfil all my dreams, but it's deprecated with no explanation what to use in its place. Can someone point me to what I should use now?
    s
    • 2
    • 3
  • b

    Brendan Weinstein

    11/16/2022, 2:02 PM
    Seeing this swallowed stacktrace show up only on iOS, not on android, with new memory model in coroutines 1.6.4 and kotlin 1.7.21. Anyone have suggestions for how to further debug+troubleshoot?
    0  libsystem_kernel.dylib  ___pthread_kill
    1  libsystem_pthread.dylib _pthread_kill
    2  libsystem_c.dylib       _abort
    3  BaseBetaiOS             konan::abort() (BaseBetaiOS)
    4  BaseBetaiOS             (anonymous namespace)::terminateWithUnhandledException(ObjHeader*)::$_1::operator()() const (BaseBetaiOS)
    5  BaseBetaiOS             void (anonymous namespace)::$_0::operator()<(anonymous namespace)::terminateWithUnhandledException(ObjHeader*)::$_1>((anonymous namespace)::terminateWithUnhandledException(ObjHeader*)::$_1) (BaseBetaiOS)
    6  BaseBetaiOS             (anonymous namespace)::terminateWithUnhandledException(ObjHeader*) (BaseBetaiOS)
    7  BaseBetaiOS             (anonymous namespace)::processUnhandledException(ObjHeader*) (BaseBetaiOS)
    8  BaseBetaiOS             kfun:kotlinx.coroutines#handleCoroutineException(kotlin.coroutines.CoroutineContext;kotlin.Throwable){} (BaseBetaiOS)
    9  BaseBetaiOS             kfun:kotlinx.coroutines.StandaloneCoroutine.handleJobException#internal (BaseBetaiOS)
    10 BaseBetaiOS             kfun:kotlinx.coroutines.JobSupport.finalizeFinishingState#internal (BaseBetaiOS)
    11 BaseBetaiOS             kfun:kotlinx.coroutines.JobSupport.tryMakeCompleting#internal (BaseBetaiOS)
    12 BaseBetaiOS             kfun:kotlinx.coroutines.JobSupport#makeCompletingOnce(kotlin.Any?){}kotlin.Any? (BaseBetaiOS)
    13 BaseBetaiOS             kfun:kotlinx.coroutines.AbstractCoroutine#resumeWith(kotlin.Result<1:0>){} (BaseBetaiOS)
    14 BaseBetaiOS             kfun:kotlin.coroutines.native.internal.BaseContinuationImpl#resumeWith(kotlin.Result<kotlin.Any?>){} (BaseBetaiOS)
    15 BaseBetaiOS             kfun:kotlinx.coroutines.DispatchedTask#run(){} (BaseBetaiOS)
    16 BaseBetaiOS             kfun:kotlinx.coroutines.DarwinGlobalQueueDispatcher.$dispatch$lambda$0$FUNCTION_REFERENCE$693.$<bridge-UNN>invoke(){}#internal (BaseBetaiOS)
    17 BaseBetaiOS             ___6f72672e6a6574627261696e732e6b6f746c696e783a6b6f746c696e782d636f726f7574696e65732d636f7265_knbridge762_block_invoke (BaseBetaiOS)
    18 libdispatch.dylib       __dispatch_call_block_and_release
    19 libdispatch.dylib       __dispatch_client_callout
    20 libdispatch.dylib       __dispatch_root_queue_drain
    21 libdispatch.dylib       __dispatch_worker_thread2
    22 libsystem_pthread.dylib __pthread_wqthread
    i
    • 2
    • 1
  • p

    Panos

    11/16/2022, 7:09 PM
    Hello, I’m trying to use an
    Executors.newFixedThreadPool(8)
    to create a pool of threads that are meant to indefinitely process incoming SQS messages. It seems from my tests that tasks are submitted constantly to the pool without waiting for one or more of the 8 allocated threads to finish. I’m not using shutdown as I do not want to shutdown this pool but instead use it indefinitely but wait when it is full. Any ideas?
    c
    g
    • 3
    • 4
  • e

    escodro

    11/16/2022, 7:47 PM
    Hey! 👋 I have the following (simplified) code:
    fun addItem(item: String) {
        viewModelScope.launch {
            repository.saveDataInRoom(item)
            interactor.sendNotification(item)
            interactor2.updateWidget(item)
        }
    }
    The “addItem” screen is a Bottom Sheet that is dismissed after the user adds an item. Since the
    saveDataInRoom()
    is a heavy operation, by the time it ends the execution the coroutine was already cancelled by passing on
    ViewModel#onCleared()
    . Then no code after that is executed after that command. Any suggestions on how to ensure that everything is executed? Thanks!
    k
    j
    +2
    • 5
    • 8
  • a

    Anders Sveen

    11/17/2022, 6:43 AM
    Hi! I'm not too intimate with Coroutines, but I am trying write a few wrappers for JDBI that makes it play nicer with them. There are tons of obstacles to this, but first I want a test to provoke the problem to show other people... And to do that, I want to make sure two operations run on different threads. I need this because JDBI has a built in thread local (which I want to get rid of by showing the problem). But they end up executing on the same thread... Is my assumption right that the following code could execute on different threads in a system with more traffic? If so, how can I write a test that uses coroutines, but guarantees to run on different threads as to provoke the problem?
    @Test
        fun shouldExecuteOnDifferentThreads() {
            runBlocking {
                // Some blocking DB operation
                val firstThread = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                    Thread.currentThread()
                }
    
                // Another blocking DB operation
                val secondThread = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                    Thread.currentThread()
                }
                assertThat(firstThread).isNotSameAs(secondThread)
            }
        }
    b
    j
    • 3
    • 5
  • j

    jean

    11/17/2022, 10:19 PM
    I have the following functions
    suspend fun loadData(
        scope: CoroutineScope,
        state: MutableStateFlow<ViewState>,
    ) {
        state.update {
            it.copy(
                data1 = it.data1.copy(status = AsyncDataStatus.LOADING),
                data2 = it.data2.copy(status = AsyncDataStatus.LOADING),
                data3 = it.data3.copy(status = AsyncDataStatus.LOADING),
            )
        }
    
        scope.launch { loadData1FromRepository(state) }
        scope.launch { loadData2FromRepository(state) }
        scope.launch { loadData3FromRepository(state) }
    }
    
    private suspend fun loadData1(
        state: MutableStateFlow<ViewState>
    ) = loadData1FromRepository().collect { result ->                // this is a flow of 2 either values coming from a database and network
        state.update { it.copy(data1 = newAsyncValue(result)) }
    }
    when running tests, I get a time out exception
    state.test {
        val loading = awaitItem()
        assertEquals(
            expected = initial.copy(
                data1 = initial.data1.copy(status = AsyncDataStatus.LOADING),
                data2 = initial.data2.copy(status = AsyncDataStatus.LOADING),
                data3 = initial.data3.copy(status = AsyncDataStatus.LOADING),
            ),
            actual = loading,
        ) // this passes correctly
    
        val data1Loaded = awaitItem()
        assertEquals(
            expected = loading.copy(
                data1 = initial.data1.copy(
                    status = AsyncDataStatus.SUCCESS,
                    data = someData1,
                ),
            ),
            actual = data1Loaded,
        ) // here I get the time out
    What am I supposed to do inorder to make the coroutines complete and return a value before the timeout?
    m
    • 2
    • 2
  • t

    TW

    11/18/2022, 12:35 PM
    Hello, i need advice. There is some file downloader. I want to manage each download (cancel, enqueue etc.). I made something like sample (see thread). But I doubt it is right to manipulate jobs in this way. Maybe there is some more elegant way in coroutines or sample is ok?
    g
    • 2
    • 2
  • t

    Tran Thang

    11/19/2022, 11:00 AM
    Hi guys, Does you guys know what the difference between coroutineScope and viewmodelScope?
    j
    • 2
    • 8
  • d

    dephinera

    11/21/2022, 6:04 AM
    Hello, I'm working on a project that has a lot of RxJava, but we want to migrate to coroutines and Flow. So far I find that the two have nice interoperability. However I was wondering: does it make sense to set coroutines dispatchers as default Rx Schedulers through RxJavaPlugins by using Dispatcher.asScheduler? Is there a significant overhead if we don't? The project is an Android app
    b
    • 2
    • 2
  • n

    natario1

    11/22/2022, 11:07 AM
    What’s the performance of
    currentCoroutineContext()
    ? I imagine it doesn’t suspend despite being
    suspend
    and should return immediately, just fetching some compiler generated field, no extra allocations. Is this right?
    s
    • 2
    • 2
  • d

    dead.fish

    11/22/2022, 12:39 PM
    Imagine I have a
    suspend
    function that feeds a
    StateFlow
    with one or two different values, in quick succession. How would I test this with Coroutines 1.6? Issue is that during the test I only see the second emitted value and the first is already gone. I tried different things using different dispatches, but nothing worked out unfortunately.
    d
    c
    • 3
    • 9
  • b

    Bruno G Tavares

    11/22/2022, 6:11 PM
    I have a few questions on handling coroutines cancellations: do we still need to write runSuspendCatching or this was fixed? Also if we would use arrow's
    try
    would we have to account for the coroutine or it would catches that?
    s
    j
    d
    • 4
    • 5
  • j

    Jhonatan Sabadi

    11/22/2022, 8:27 PM
    How can I measure suspend function execution? I wanna compare before and after changes.
  • j

    Jeff Lockhart

    11/23/2022, 1:30 AM
    I have a suite of common tests that run on iOS and JVM that use
    kotlinx-coroutines-test
    . Each test is run within a
    runTest()
    coroutine. All the tests execute and pass on JVM. On iOS they usually pass as well, but often (~30% of the time) one of the tests hangs, blocking the test suite's completion. I've seen almost all the tests cause this, from the first to the last, so it's not caused by a specific test. If I add a print statement to the bottom of each of the
    runTest()
    calls, the print statement is always executed, so it's hanging after the test code completes, but
    runtTest()
    apparently isn't returning for some reason. Any idea what could be the cause of this? The code is based on this test suite from SQLDelight, but using multiplatform paging and a different database.
    a
    d
    • 3
    • 22
  • a

    Asad Mehmood

    11/23/2022, 9:57 AM
    Hi I'm trying to create a native implementation of a coroutine (
    native suspend fun
    ) in rust via JNI. I've managed to create a function which starts an async rust fn in another thread and immediately returns
    COROUTINE_SUSPENDED
    to kotlin. The question is: Does
    resumeWith
    run in the native thread (Does is treat the native thread as a dispatcher) or dispatch back to the kotlin dispatcher? I'm using a single thread to call resumeWith as setting up and tearing down JNI Threads are expensive and I would like to know whether its cheap or if it could end up starving other calls to resumeWith? Should I be using a dynamic blocking threadpool to call resumeWith? See for rust code example: https://github.com/mehmooda/suspendlib/blob/main/src/lib.rs
    s
    • 2
    • 5
  • l

    Lukas Lechner

    11/23/2022, 3:07 PM
    Hi! I created a new video about “What is a Flow in Kotlin?”

    https://youtu.be/TvdF566t2Y8▾

  • l

    Lukas Lechner

    11/24/2022, 11:17 AM
    How can a SharedFlow drop its emission when the downstream is busy?
    suspend fun main(): Unit = coroutineScope {
    
        val sharedFlow = MutableSharedFlow<Int>()
    
        launch {
            sharedFlow
                .collect {
                println("Process $it")
                delay(1000)
                println("$it processed")
            }
        }
    
        launch {
            // 1 should be processed
            sharedFlow.emit(1)
            println("sharedFlow emits 1")
    
            // 2 should not be processed since downstream is busy
            sharedFlow.emit(2)
            println("sharedFlow emits 2")
    
            // 3 should be processed again
            delay(2000)
            sharedFlow.emit(3)
            println("sharedFlow emits 3")
        }
    }
    I tried BufferOverflow.DROP_LATEST, but there we need to have a buffer value > 0
    c
    c
    +2
    • 5
    • 5
  • g

    George

    11/24/2022, 5:19 PM
    Hello folks, i am a bit confused with the below code, how come it does not print the emitted value?
    open class WrapperFlow {
        private val hotFlow = MutableSharedFlow<Int>()
    
        fun getFlow(): Flow<Int> = hotFlow
    
        @Transactional
        open suspend fun emit() {
            hotFlow.emit(10)
        }
    }
    
    suspend fun main() = coroutineScope {
        println("hi")
        val wrapperFlow = WrapperFlow()
        val job1 = launch {
            wrapperFlow.getFlow().collect {
                println("job1: $it")
            }
        }
        wrapperFlow.emit() // does not print job1: $it
        job1.cancelAndJoin()
    }
    Thanks in advance for any answers !
    f
    • 2
    • 4
  • s

    Slackbot

    11/27/2022, 12:10 AM
    This message was deleted.
    j
    j
    +2
    • 5
    • 10
  • s

    Stylianos Gakis

    11/27/2022, 1:31 AM
    Trying to understand why two code snippets work the way they do regarding SupervisorJob and cancellation of children. More in thread
    s
    • 2
    • 3
  • d

    dimsuz

    11/28/2022, 1:24 PM
    How does one combine
    Job
    's ?
    fun allJobs(): Job {
      val job1: Job
      val job2: Job
      val job3: Job
      return combine(job1, job2, job3) // HOW?
    }
    
    fun main() {
      allJobs().cancel() // cancels all 3 jobs
    }
    Is it possible or do I have to use some pattern which is similar to this?
    s
    b
    +2
    • 5
    • 18
  • d

    dead.fish

    11/29/2022, 4:58 PM
    I’m a little puzzled - I try to build a base thing that offers a
    val flow: StateFlow<T>
    to consumers, while individual implementations can fill in the initial state via some
    protected abstract suspend fun initialState(): T
    . But I can’t get lazy initialization working, i.e. my backing
    MutableSharedFlow<T>(replay = 1)
    needs suspending to be converted into a
    StateFlow
    or needs the initial value being given again (repeated), which defeats the purpose, i.e.
    val flow: StateFlow<T> get() = backingFlow.onStart { emit(initialState()) }.stateIn(someScope)
    does not work, because
    stateIn(someScope)
    is suspending. What am I doing wrong?
    s
    c
    • 3
    • 4
  • u

    ursus

    11/30/2022, 12:16 AM
    Is there some sugar for
    try catch
    which doesn’t catch
    CancellationException
    ? or should I not care to rethrow that?
    j
    s
    +2
    • 5
    • 11
  • c

    czuckie

    11/30/2022, 12:52 AM
    I want to simulate the following behaviour using coroutines:
    val executor = Executors.singleThreadExecutor()
    
    fun oneAtATime(workToDo: Boop) {
       return executor.submit {
          doSomethingWIthThe(workToDo)
       }.get()
    }
    Where
    oneAtATime(...)
    may be invoked by multiple threads, but will only allow one operation at a time due to the single thread executor.
    j
    e
    +2
    • 5
    • 10
  • c

    czuckie

    11/30/2022, 1:37 PM
    is there anyway to query a
    Channel
    for an amount of time before abandoning the operation? None of the
    receive*
    functions seem to have what I want.
    d
    • 2
    • 3
  • u

    ursus

    12/01/2022, 11:57 PM
    Is there any guarantee to
    delay
    ? Atleast that it won't resume sooner than the deadline?
    f
    g
    • 3
    • 4
  • u

    ursus

    12/02/2022, 2:48 AM
    I have a stream of `Meeting`s, where a meeting struct has a
    beginsAt: Timestamp
    on it I need to render a list of those meetings, and color red those which are say, 15 minutes before beginning. Now, I’d best like to use a combineLatest, however that requires a “time” stream to combine with. I could have a stream which emits every say seconds, but that feels like a waste So my attempt, I observe the stream, and calculate the delta time from now and “15min before beginning”, and
    timer
    to emit then. Now, the question is, should I use this only as a “tickle” into the combineLatest, and let it’s combiner to reevaluate the “15min before beginning” condition in it
    combine(meetings, timer, ::combiner)
    Or, should I treat
    timer
    as the trusted, and then just set the meeting’s color directly, i.e. don’t reevaluate the condition? -- I like the former, however it requires for the
    timer
    not emit before the given deadline. Is it to be trusted to not do so?
    u
    • 2
    • 32
  • t

    Tower Guidev2

    12/02/2022, 1:38 PM
    Hi iam attempting to implement MVI in my current Android compose application My composable screen has an associated viewmodel which holds two flows that i combine and collect as follows:-
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    c
    f
    p
    • 4
    • 21
  • m

    Marc Knaup

    12/02/2022, 5:45 PM
    Is there a way to use
    TestCoroutineScheduler.advanceTimeBy()
    and get a callback whenever the
    currentTime
    changes in order to execute side-effects? Or at least query the next event time?
    d
    • 2
    • 5
Powered by Linen
Title
m

Marc Knaup

12/02/2022, 5:45 PM
Is there a way to use
TestCoroutineScheduler.advanceTimeBy()
and get a callback whenever the
currentTime
changes in order to execute side-effects? Or at least query the next event time?
d

Dmitry Khalanskiy [JB]

12/03/2022, 11:01 AM
No such mechanisms at the moment, and you're the first one to my knowledge to request it.
m

Marc Knaup

12/03/2022, 10:30 PM
Interesting. We need to simulate more than just coroutine timing - for example a job scheduler. So we need to have all clock simulations (coroutine scheduler, wall clock) in sync and run all side-effects of advancing time - not just coroutines.
d

Dmitry Khalanskiy [JB]

12/04/2022, 10:52 AM
If I understood correctly, this is a tough problem, and, in general, a callback would not be enough. Let's say there are three schedulers (
X
,
Y
, and
Z
) that need to have virtual time. Also, let's, as you propose, designate the time as seen by
X
as the real time.
Y
is registered as the first thing to get a callback for a time change from
X
,
Z
is registered as the second thing. •
X
has a task scheduled in 10 seconds, •
Y
has a task scheduled in 9 seconds, •
Z
has a task scheduled in 2 seconds.
X
proceeds to grab another task from the queue and announces: "The virtual time is now 10".
Y
urgently runs the task, and then,
Z
starts running its task. We're left with an insane and completely unrealistic interleaving. The Proper™ thing to do here would be to have a queue of tasks shared by all three things and advance the virtual time for all of them. Here, the knowledge of when the next task is planned would help you, that's a nice use case for that. The Proper™ thing may be too difficult to do though, depending on the provided APIs of
X
,
Y
, and
Z
, so maybe something like this could be the best way instead:
val timerResolution = 50.milliseconds
while (testNotFinished) {
  X.advanceTimeBy(timerResolution)
  Y.advanceTimeBy(timerResolution)
  Z.advanceTimeBy(timerResolution)
}
m

Marc Knaup

12/04/2022, 12:16 PM
Thank you Dmitry. Interesting idea. Using a certain resolution could certainly work reasonably well (we’d have 630,720,000 iterations for one year). Your example assumes that X, Y and Z all behave like the test scheduler. For example I know in advance the next event timestamp for the job scheduler. It’s just the test coroutine scheduler that keeps such info private. Something like that might also work if the test coroutine scheduler would expose info about the next pending event time:
fun advanceTimeBy(delay: Long) {
   var remainingDelay = delay

   while (true) {
      val delayToNextEvent = listOfNotNull(X.delayToNextEvent, Y.delayToNextEvent, Z.delayToNextEvent)
         .minOrNull()
         ?.takeIf { it <= remainingDelay }
         ?: break
      X.advanceTimeBy(delayToNextEvent)
      Y.advanceTimeBy(delayToNextEvent)
      Z.advanceTimeBy(delayToNextEvent)

      remainingDelay -= delayToNextEvent
   }
}
d

Dmitry Khalanskiy [JB]

12/04/2022, 1:34 PM
There's a missing
X.advanceTimeBy(remainingDelay)
and such at the end so the virtual time is properly updated, but other than that, yeah, I agree that this would also work… unless someone is adding new tasks to
X
,
Y
, and
Z
in parallel to
advanceTimeBy
. So, the tricky thing with this API is the existence of code that runs outside the test dispatchers. I think this issue relates to https://github.com/Kotlin/kotlinx.coroutines/issues/3189, which asks for notifications about the scheduler being idle, but this could be extended to also providing the information about the next pending task when not idle. It seems that, if we decide how to treat the code in other threads concerning idleness, both problems can be solved.
View count: 7