https://kotlinlang.org logo
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
  • t

    Tran Thang

    02/22/2023, 12:47 PM
    have 3 api as below:
    class MovieRepositoryImpl(private val api: MovieApi):MovieRepository {
        override suspend fun fetchMovie(): Movie {
          return api.fetchMovie()
        }
    
        override suspend fun fetchMoviePopular(): MoviePopular {
           return api.fetchMoviePopular()
        }
    
        override suspend fun fetchFaves(): Faves {
            return api.fetchFaves()
        }
    }
    I am wanting to call the above 3 api at the same time with the following condition: if the 1st api fails, the following 2 apis will not be called, but if the 1st api succeeds, the 2nd api fails, still call the 3rd API In short, if the 1st api fails, don't call the rest of the apis, but if the 2nd api fails, continue to call other apis
    fun fetchAll():Triple<Movie,MoviePopular,Faves> = supervisorScope {
            val movieDeferred = async { fetchMovie() }
            val moviePopularDeferred = async { fetchMoviePopular() }
            val favesDeferred = async { fetchFaves() }
            val movie = movieDeferred.await()
            val moviePopular = moviePopularDeferred.await()
            val faves = favesDeferred.await()
            return@supervisorScope Triple(movie,moviePopular,faves)
        }
    so can anyone help me to solve this problem.
    s
    • 2
    • 2
  • r

    Ryan Smith

    02/22/2023, 11:39 PM
    If I want to make a child coroutine scope for my Repository so that the coroutines it launches are tied to application lifecycle rather than that of a view model or something more narrow what is the correct way to do that? Something like this?
    // MyRepository.kt
    class MyRepository<T>(coroutineScope: CoroutineScope) {
        private val scope = couroutineScope + Dispatchers.Default
        private val dataSource: DataSource<T> = DataSource()
    
        fun add(newValue: T) {
            scope.launch {
                dataSource.new(newValue)
            }
        }
    }
    
    // Example usage in a Compose Desktop app
    // Main.kt
    @Composeable
    @Preview
    fun App() {
        val appScope = rememberCoroutineScope { Dispatchers.Main }
        val repository = MyRepository(appScope)
        MainScreen(repository)
    }
    c
    • 2
    • 9
  • l

    Lukas Lechner

    02/23/2023, 11:38 AM
    Is it okay to store data in the CoroutineContext so that we don’t have to pass it from suspend function to suspend function? The use case is that we have a backend application, and we currently store authentication information at the beginning of each request so that we are able to receive them from every suspend function without needing to pass them as paremeters all the time…
    o
    c
    m
    • 4
    • 7
  • d

    Daniele Segato

    02/23/2023, 4:43 PM
    How does Coroutine Dispatchers.Default works regarding ARM big.LITTLE CPU architecture? (this came out on an AndroidDev Discord server but apparently no one knew exactly how it worked) With this architecture the "little" slow but battery efficient cores are supposed to be used when the load is low and the "big" ones kick in when needed to give more power. I looked but couldn't find much information on what part of the OS decide when to switch between the two or how this impact user space and Android Applications. I've even trying to look at the android example here https://ui.perfetto.dev/ but I couldn't figure out how things works I just don't have enough knowledge to read those graphs. Coroutine Dispatchers.Default is initialized with
    @JvmField
    internal val CORE_POOL_SIZE = systemProp(
        "kotlinx.coroutines.scheduler.core.pool.size",
        AVAILABLE_PROCESSORS.coerceAtLeast(2),
        minValue = CoroutineScheduler.MIN_SUPPORTED_POOL_SIZE
    )
    and
    internal val AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors()
    does this means that the Default dispatcher contains both big and little cores? and assign work to do to each or the other just depending on the order they gets in? Anyone has information on how this works? Do I have any control on which profile gets chosen as a developer or am I misinterpreting the all thing and the cores are swapped under the hood by the OS transparently? Thanks in advance to whoever can help me gain a better understanding on this topic.
    p
    l
    r
    • 4
    • 6
  • j

    julian

    02/23/2023, 5:58 PM
    Does anyone have ideas for focused projects or exercise problems to solve that would serve as "deliberate practice" to develop specific mastery of Kotlin coroutines + flow? Ideally these would involve nothing of adjacent domains e.g. network calls, the Android framework etc. As narrowly focused on coroutines and flow as possible. I'm compiling a list that I'll make publicly available.
  • c

    Colton Idle

    02/23/2023, 6:36 PM
    I'm building an android app, and I'm following the "repository" pattern. Any suggestions on whether or not my functions should be suspend functions?
    class NetworkBackedBookRepository(
        private val api: ApiService,
    ) : BookRepository {
        override suspend fun getBook(id: String): Book? {
            val result = api.getBookById(id).execute()
            return result.body()?.firstOrNull()
        }
    }
    y
    c
    +2
    • 5
    • 10
  • j

    jean

    02/24/2023, 9:47 AM
    How can I feed a flow with data from another flow? Some code example :
    class PaymentViewModel(...) : ViewModel() { // in an android app
        private val _state = MutableStateFlow<PaymentStatus>()
        val state = _state.asStateFlow()
    
        fun pay() {
            ...
        }
    
        private fun payWithCard {
            paymentWithCard() // returns a flow of PaymentStatus
        }
    
        private fun payWithApp {
            payWithApp() // returns a flow of PaymentStatus
        }
    }
    How can I update
    _state
    with the data coming from
    paymentWithCard()
    and
    paymentWithApp()
    ? Do I have to use
    collect { … }
    on each of them and manually update the state?
    s
    • 2
    • 2
  • k

    kevin.cianfarini

    02/25/2023, 3:40 PM
    I'm curious what the proper way to test that a piece of code is delaying for the right amount of time is with the test scheduler. I originally thought that it was to use
    advanceTimeBy
    but since delays are skipped, using it doesn't make a difference. Is testing that
    currentTime
    has been incremented as you expect the proper approach?
    d
    r
    b
    • 4
    • 41
  • f

    fengdai

    02/28/2023, 3:34 AM
    How to construct a CoroutineScope in Java? I’m facing this error:
    k
    d
    • 3
    • 4
  • d

    Daniele B

    02/28/2023, 5:31 PM
    I have a multiplatform project: Android and Desktop. I have defined the core coroutine package in `commonMain`:
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
    on Android, the app works without the need of adding the android-specific coroutine package on
    androinMain
    on Desktop, it gives me this error:
    Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlin-coroutine-android' and ensure it has the same version as 'kotlin-coroutine-core'
    what is the reason why on Android, the target specific package is not needed?
    a
    f
    • 3
    • 3
  • j

    Jason Hartley

    02/28/2023, 5:52 PM
    I need advice. I'm updating an app that uses Threads and Runnables for a handful of background tasks that generally stay running for the lifetime of the app, but can be terminated based on various events. For example, one of these Runnables is actively receiving data from a USB accessory and passing it on to listeners, but can be killed if the USB connection is lost. The way it's currently architected is a foreground service stays running that executes these Threads/Runnables on a ThreadPoolExecutor. I'd like to convert this all to coroutines, but I have to admit that I have virtually no experience working with coroutines directly. What might be a good general approach for converting these Threads/Runnables to coroutines?
    c
    • 2
    • 3
  • t

    Tim Malseed

    03/01/2023, 1:21 AM
    I have a
    List<Flow<String?>>
    I’d like to emit the latest value from the first flow in the list - unless that value is null, in which case I’d like to move to the next flow. Does anyone know how to achieve this?
    e
    c
    s
    • 4
    • 25
  • u

    ubu

    03/01/2023, 11:43 AM
    Hello there! Is there a way to short cut the following code to one operator:
    override val view: Flow<WidgetView> = combine(
            expandedBranches, isWidgetCollapsed
        ) { paths, isWidgetCollapsed -> Pair(paths, isWidgetCollapsed)
        }.flatMapLatest { switchToNewFlow() based on Pair  }
    I think that creating a pair is kind of redundant. But every time either of these two flows emits a new value, I need to switch to a different flow. Thanks!
    c
    • 2
    • 4
  • c

    Christophe Dongieux

    03/02/2023, 8:18 PM
    Hi! I don’t understand why this Coroutine test with delays fails, do you have any idea?
    @Test
    fun `Foobar is foo`() = runTest {
        val job = launch {
            println("Coroutine 1: Going to sleep for 3000. currentTime = $currentTime")
            delay(3000)
            println("Coroutine 1: Delay is over. currentTime = $currentTime")
        }
        launch {
            println("Coroutine 2: Going to sleep for 1000. currentTime = $currentTime")
            delay(1000)
            println("Coroutine 2: Delay is over, cancelling other Coroutine. currentTime = $currentTime")
            job.cancel()
        }
        advanceTimeBy(500)
        println("advance 500: currentTime 1 = $currentTime")
    
        advanceTimeBy(500)
        println("advance 500: currentTime 2 = $currentTime")
    
        advanceUntilIdle()
        println("advanceUntilIdle: currentTime 3 = $currentTime")
    
        assertEquals(1000, currentTime)
    }
    The output is:
    Coroutine 1: Going to sleep for 3000. currentTime = 0
    Coroutine 2: Going to sleep for 1000. currentTime = 0
    advance 500: currentTime 1 = 500
    advance 500: currentTime 2 = 1000
    Coroutine 2: Delay is over, cancelling other Coroutine. currentTime = 1000
    advanceUntilIdle: currentTime 3 = 3000
    
    expected:<1000> but was:<3000>
    Expected :1000
    Actual   :3000
    As Coroutine 1 is canceled I don’t understand why
    currentTime 3
    is 3000 instead of 1000.
    m
    • 2
    • 6
  • r

    Rohan Maity

    03/03/2023, 10:06 AM
    Hi, my coroutine job immediately gets cancelled even before staring. Now I am not sure what could be reasons for this. What could be reasons for coroutine to get cancelled even before it is cancelled
    private fun CoroutineScope?.launchWithNullCheck(
            block: suspend () -> Unit
        ) {
            this?.let {
                Log.d("FUI", "Scope not null")
                val job = launch {
                    Log.d("FUI", "executing block not null")
                    block()
                }
                Log.d("FUI", "job isActive ${job.isActive}, isCompleted: ${job.isCompleted}, isCancelled: ${job.isCancelled}")
            }
    }
    s
    • 2
    • 13
  • c

    Colton Idle

    03/04/2023, 7:32 AM
    I've got 2 coroutines making a network call. call A and call B. I want to know 3 things: 1. When a completes 2. When b completes 3. When both a AND b completes is there an easy way to do this with coroutines? I know I can use awaitAll to wait for option 3, but I also want to do stuff when A and B are done separately.
    f
    j
    +2
    • 5
    • 14
  • p

    Patrick Steiger

    03/05/2023, 11:55 PM
    Why is
    subscriptionCount
    a property of
    MutableSharedFlow
    instead of
    SharedFlow
    ?
    e
    • 2
    • 4
  • b

    Bradleycorn

    03/06/2023, 9:24 PM
    I’ve got a suspending function in an object/class that runs “indefinitely” (i.e. until it’s calling coroutine is canceled). A contrived example might be:
    object MyObject {
    
        suspend fun repeatWork() {
            while (true) {
                // do something
                delay(5_000L)
            }
        }
    }
    That’s fine, but now multiple things can call it, and do “multiple copies” of the work:
    class SomeClass {
        fun doWork() {
            someClassScope.launch { MyObject.repeatWork() } 
        }
    }
    
    class AnotherClass {
        fun doAnotherWork() {
            anotherClassScope.launch { MyObject.repeatWork() } 
        }
    }
    
    SomeClass().doWork()
    AnotherClass().doAnotherWork()
    I’m trying to ensure that only one “instance” of the repeatWork routine is running at a time, no matter how may things try to call it. I was thinking something like this:
    object MyObject {
    
        private var repeatWorkJob: Job? = null
    
        suspend fun repeatWork() = coroutineScope {
            if (repeatWorkJob?.isActive == true) return
       
            repeatWorkJob = launch {
                while (true) {
                    // do something
                    delay(5_000L)
                }
            }
        }
    }
    Is this the best/right way to ensure there’s only one “instance” of the repeatWork routine running at one time?
    f
    e
    +2
    • 5
    • 19
  • u

    ursus

    03/07/2023, 2:55 PM
    Hey,
    class FooViewModel(private val appScope: CoroutineScope) : ViewModel() {
    
        fun fooClicked() {
            viewModelScope.launch {
                delay(2000)
                withContext(appScope.coroutineContext) { <---------------------------
                    // Should run even when view user clicks back (i.e. view model cleared)
                    delay(2000)
                }
            }
        }
    }
    Is this a correct way to run something even after view model scope is cancelled? (view model cleared on back press) I was used to just
    appScope.launch { .. }
    i.e. to launch a new couroutine in the "higher" scope explicitly This way of
    withContext
    seems to work as well but feels wrong
    Opinions? Doesn't it leak
    viewmodel this
    during the lambda execution?
    u
    s
    +2
    • 5
    • 47
  • s

    Sam

    03/07/2023, 11:11 PM
    I don't remember there being two
    CancellationExceptions
    ... They're not aliases of each other... Does either one work?
    t
    • 2
    • 8
  • n

    natario1

    03/08/2023, 10:46 AM
    Does anyone from JB know when the next
    kotlinx.coroutines
    release is scheduled for? I see very little activity in the master branch, previous release was on July 2022. At the same time we are eager to try the new android native targets.
    kotlinx-atomicfu
    made a special release just for these, could coroutines do the same?
    d
    • 2
    • 4
  • z

    Zoltan Demant

    03/09/2023, 6:10 AM
    Just curious: what happens if youre emitting a class with mutable properties to a
    StateFlow
    ? Id think that the first emission comes through, but if you then edit the class and emit it anew, nothing will come through given how StateFlow compares equals before emitting new items?
    a
    t
    p
    • 4
    • 9
  • r

    Robert Jaros

    03/09/2023, 2:35 PM
    https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.7.0-Beta
    l
    • 2
    • 1
  • t

    Tower Guidev2

    03/09/2023, 4:32 PM
    I thought I understood kotlin coroutines 🤦‍♂️
    s
    p
    r
    • 4
    • 18
  • v

    Vsevolod Tolstopyatov [JB]

    03/09/2023, 4:50 PM
    📣 📣 📣 kotlinx.coroutines 1.7.0-Beta is here! This is a Beta of the major release that contains multiple significant reworks and improvements: • Much more efficient new
    Channel
    ,
    Mutex
    and
    select
    implementations • JPMS support • Merge of
    kotlinx-coroutines-core
    and
    kotlinx-coroutines-jdk8
    • Partial stabilization and notable improvements of
    kotlinx-coroutines-test
    • More K/N support: all official targets, better dispatchers,
    <http://Dispatchers.IO|Dispatchers.IO>
    And many more! Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.7.0-Beta
    c
    r
    • 3
    • 2
  • d

    Daniel

    03/10/2023, 6:12 PM
    Hello all, I am new at kotlin, Is this the correct way that the flow is executed?
    suspend fun Logout(token: String) {
        val userId = appService.currentUser!!.id       ///// this will execute 1st
        realm.write {                                  ///// this will execute 2nd
            var user = query<UserInfo>("_id = $0", userId).first().find()
            if (user != null) {
                user = findLatest(user)!!.also {
                    it.FCMToken.remove(token)
                }
                copyToRealm(user)
            }
        }
        withContext(Dispatchers.Default) {             ///// this will execute 3rd
    
            realm.syncSession.uploadAllLocalChanges()  ///// this will execute 4rd
    
            appService.currentUser?.logOut()           ///// this will execute 5th
        }
    }
    Are they executed in a linear way?
    s
    u
    e
    • 4
    • 4
  • k

    Kshitij Patil

    03/14/2023, 5:16 AM
    I’m trying to implement concurrent system using actor models. Not able to wrap my head around sending delayed message to actor. Attaching my snippet to implement the same. Is this correct?
    ActorDelayedMessage.kt
    u
    • 2
    • 9
  • s

    Slackbot

    03/14/2023, 11:19 AM
    This message was deleted.
    u
    d
    • 3
    • 23
  • n

    natario1

    03/14/2023, 12:16 PM
    I’m struggling to redesign this thing:
    class Processor {
        private val condition1 = MutableStateFlow(false)
        private val condition2 = MutableStateFlow(false)
        private suspend fun process(): Processed { ... }
        init {
            someScope.launch {
                combine(condition1, condition2) { a, b -> a || b }
                    .collectLatest { process() }
            }
        }
        fun setCondition1() { condition1.value = true }
        fun setCondition2() { condition2.value = true }
    }
    When the user changes one of the conditions, I would like to • know if this change did not trigger a
    process()
    (for example, throw if not) • return something like a
    Deferred<Processed>
    to be (optionally) awaited. Does anyone have any idea on how to achieve this?
    d
    • 2
    • 1
  • j

    jean

    03/14/2023, 12:52 PM
    I have the following code and I want to make sure the callback is unregistered. How can I trigger
    awaitClose
    from my unit test ? I tried to cancel
    testScope
    but that triggers a
    ClosedReceiveChannelException: Channel was closed
    since turbine gets also canceled.
    private fun someApiCallbackToFlow(api: API) = callbackFlow {
        val callback = object : ApiCallback {
            override fun next(data: Int) {
                trySend("Success")
            }
        }
        api.register(callback)
        awaitClose {
            println("callback unregistered")
            api.unregister(callback)
        }
    }
    
    
    @OptIn(ExperimentalTime::class)
    @Test
    fun test() = testScope.runTest {
        val api = SomeApi()
        val flow = someApiCallbackToFlow(api)
        flow.test {
            assertEquals(1, api.callbacks.size)
            api.getData()
            assertEquals("Success", awaitItem())
            // how can I check there isn't any callback here?
        }
    }
    p
    • 2
    • 6
Powered by Linen
Title
j

jean

03/14/2023, 12:52 PM
I have the following code and I want to make sure the callback is unregistered. How can I trigger
awaitClose
from my unit test ? I tried to cancel
testScope
but that triggers a
ClosedReceiveChannelException: Channel was closed
since turbine gets also canceled.
private fun someApiCallbackToFlow(api: API) = callbackFlow {
    val callback = object : ApiCallback {
        override fun next(data: Int) {
            trySend("Success")
        }
    }
    api.register(callback)
    awaitClose {
        println("callback unregistered")
        api.unregister(callback)
    }
}


@OptIn(ExperimentalTime::class)
@Test
fun test() = testScope.runTest {
    val api = SomeApi()
    val flow = someApiCallbackToFlow(api)
    flow.test {
        assertEquals(1, api.callbacks.size)
        api.getData()
        assertEquals("Success", awaitItem())
        // how can I check there isn't any callback here?
    }
}
p

Patrick Steiger

03/15/2023, 3:03 AM
https://cashapp.github.io/turbine/docs/0.x/turbine/app.cash.turbine/-receive-turbine/cancel.html
You can launch a new coroutine to run the turbine
test
And then just cancel it , join, and verify the api unregister method was called
runTest {
  coroutineScope {
    launch {
      flow.test {
        …
        cancel()
      }
    }
  }
  // verify unregister
}
Actually launching a new coroutine isn’t even necessary because the .test turbine API launches its own coroutine so:
runTest {
  var called = false
  callbackFlow<Nothing> {
    awaitClose { called = true }
  }.test {
    cancel()
  }
  assertTrue(called)
}
This passes
j

jean

03/15/2023, 8:05 AM
It worked, thanks!
View count: 4