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

    Derek Berner

    10/08/2019, 5:05 PM
    Hi, are there good `suspend`ing equivalents for
    ConcurrentHashMap
    and
    ReadWriteLock
    in a library anywhere?
    z
    m
    15 replies · 3 participants
  • r

    Robert Jaros

    10/08/2019, 5:42 PM
    how to convert
    Flux<T>
    to
    Channel<T>
    ?
    z
    17 replies · 2 participants
  • p

    Paul Woitaschek

    10/09/2019, 7:26 AM
    Why donesn't this compile?
    fun functionImpl(a: Int, b: String) {}
    
    fun nonSuspending(function: (Int, String) -> Unit) {}
    fun suspending(function: suspend (Int, String) -> Unit) {}
    
    fun test() {
      nonSuspending(::functionImpl)
      suspending(::functionImpl)
    }
    m
    e
    5 replies · 3 participants
  • y

    ylemoigne

    10/09/2019, 8:33 AM
    Another coroutine misunderstanding for me. I don't understand ; why
    In 'uncaughtExceptionHandler' ...
    is called ?
    Untitled
    e
    8 replies · 2 participants
  • j

    Jan Skrasek

    10/09/2019, 1:04 PM
    Hi, I'm trying to consume events from my view-model in fragment and I can't realize why app is crashing:
    2019-10-09 14:49:52.581 4418-4418/my.app.id E/AndroidRuntime: FATAL EXCEPTION: main
        Process: my.app.id, PID: 4418
        kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelled}@b43ae6d
    val myEvent = Channel<Unit>(Channel.RENDEZVOUS)
    
    viewModel.myEvent.consumeAsFlow()
    	.onEach {
    		Toast.makeText(requireContext(), R.string.error, Toast.LENGTH_LONG).show()
    	}
    	.launchIn(lifecycleScope)
    1. it is not obivous what caused the crash from the stack trace; emiting to closed channel? 2. how can I workaround it?
    p
    a
    5 replies · 3 participants
  • i

    igorvd

    10/09/2019, 5:20 PM
    Hi Everyone, I work with Android and I have a usecase that I need to react when some entities changes on DB. Let's say I have 3 entities and I need to react everytime one of those entities change. I was thinking to use the Room features that allow me to return a Flow from the DAO. My doubt is how I can combine that on a single stream? Thanks in advance
    t
    v
    +1
    7 replies · 4 participants
  • m

    Matt Thiffault

    10/09/2019, 11:09 PM
    Is there something similar to RxJava's Observable.share() for [Receive]Channels? Basically make another channel that will receive all the same messages as the first.
    r
    z
    3 replies · 3 participants
  • m

    Matt Thiffault

    10/10/2019, 2:05 AM
    BroadcastChannels with non-zero capacity: are messages sent before anyone subscribes dropped? Or do they sit in the queue?
    s
    l
    +1
    4 replies · 4 participants
  • g

    groostav

    10/10/2019, 8:26 AM
    Alright so, I'm looking to use a flow to help manage text changes from a javafx UI element. I have a
    Flow<Change<oldValue: String, newValue: String>>
    and I want to have a behaviour whereby: 1. we use
    debounce
    for 200 ms, such that as fast edits are made to this text, no changes are published 2. when there is a 200ms pause, it publishes a
    Change
    with the old value from before any changes were made, and the new value after all changes 3. this can be short-circuited by "focus lost", if focus changes from true to false the 200ms wait is interrupted, a change is published right away, and any pending changes are cancelled. Anybody done something like this? Care to share? If not, care to speculate with me?
    d
    5 replies · 2 participants
  • d

    Dominaezzz

    10/10/2019, 10:19 AM
    I've come with yet another
    coroutineScope
    vs
    withContext
    question. Does
    coroutineScope
    change the
    coroutineContext
    like
    withContext
    does? (I'm referring to the intrinsic
    coroutineContext
    and not
    CoroutineScope.coroutineContext
    ). The docs aren't explicit enough to inspire confidence.
    g
    e
    6 replies · 3 participants
  • b

    bnn

    10/10/2019, 11:12 AM
    onReceiveOrNull
    defined on
    ReceiveChannel
    interface is now deprecated, and
    onReceiveOrNull
    extension function defined on
    ReceiveChannel
    is now
    ExperimentalCoroutinesApi
    . I'm trying to use extension version of onReceiveOrNull but I can't. Is there anything wrong?
    m
    3 replies · 2 participants
  • m

    Marko Mitic

    10/10/2019, 11:45 AM
    Do coroutines have some kind of a scheduler API? (Other than launching a new coroutine with
    delay()
    )
    e
    d
    +4
    17 replies · 7 participants
  • p

    Paul Woitaschek

    10/11/2019, 6:27 AM
    Wow so after several hours of debugging I finally found something:
    RxJavaPlugins.setErrorHandler { }
        val flow = rxSingle<Unit> { throw IOException("") }.toFlowable().asFlow()
        runBlocking {
            repeat(10000) {
                combine(flow, flow) { _, _ -> Unit }
                    .catch {}
                    .collect { }
            }
        }
    Why does this crash?
    b
    e
    +1
    4 replies · 4 participants
  • m

    miguelsesma

    10/11/2019, 9:35 AM
    Hello, I have a doubt about channels. I have this code running flawlessly for receiving live information using websockets with Tinder.Scarlet library and its coroutines adapter:
    private val job = Job()
        private val coroutineContext = job + Dispatchers.Main
        private val scope: CoroutineScope = CoroutineScope(coroutineContext)
    
       override fun onResume() {
            super.onResume()
            scope.launch { subscribe() }
        }
    
        private suspend fun subscribe() {
            dataStore.subscribe()
             val channel: ReceiveChannel = dataStore.receiveMessage()
            for (message in channel) {
                when (message.type) {
                    "error" -> textView_scrollable.addTextNl("error: ${message.message}")
                    "ticker" -> textView_scrollable.addTextNl("ticker: ${message.sequence}, ${message.productId}, ${message.price}")
                }
            }
        }
    
        override fun onPause() {
            dataStore.unsubscribe()
            job.cancel()
            super.onPause()
        }
    But I have tried the same using
    consumeEach
    instead the for loop:
    private suspend fun subscribe() {
           dataStore.subscribe()
            val channel: ReceiveChannel = dataStore.receiveMessage()
           channel.cosumeEach { message ->
               when (message.type) { 
                   "error" -> textView_scrollable.addTextNl("error: ${message.message}")
                   "ticker" -> textView_scrollable.addTextNl("ticker: ${message.sequence}, ${message.productId}, ${message.price}")
               }
           }
       }
    It still works receiving the information, but when I cancel the job I get a
    JobCancellationException
    .
    consumeEach
    Documentation says:
    Performs the given action for each received element and cancels the channel after the execution of the block. If you need to iterate over the channel without consuming it, a regular for loop should be used instead.
    I'm not sure what it means with cancels the channel after the execution of the block. Maybe it is related. I have tried other things like
    try-finally
    ,
    NonCancellable
    ,
    SupervisorScope
    ... But if I get rid of the exception I get a memory leak in exchange because the coroutine remains alive after the fragment dies. I know that probably is something I'm understanding badly. But after reading everything I have found, I'm still lost.
    s
    2 replies · 2 participants
  • s

    Sebouh Aguehian

    10/11/2019, 1:21 PM
    Can someone please explain the result of this small snippet?
    s
    p
    21 replies · 3 participants
  • d

    Dico

    10/11/2019, 4:32 PM
    I worked out how to keep application alive until all tasks are completed. Is there a better way to do this with coroutines though?
    private val termination = CountDownLatch(1)
    private val scope = dispatcher + Job().apply {
        thread {
            // use non-dameon thread to keep application alive until all tasks completed.
            termination.await()
            while (children.any { it.isActive }) Thread.sleep(50)
        }
    }
    
    fun shutdown() {
        termination.countDown()
    }
    🙀 1
    s
    g
    +1
    33 replies · 4 participants
  • s

    SrSouza

    10/12/2019, 2:04 PM
    Hi guys, can someone explain what is behind of the
    delay
    ? I want to know because when a launch a new job in Dispatchers.Main and use Thread.sleep, the codes blocks, and its okay, this make sense, but, how
    delay
    doesn't block when I use it in the Dispatchers.Main? He create a new single thread pool and waits three and use suspendCoroutine and resume after that?
    d
    l
    +1
    11 replies · 4 participants
  • z

    zak.taccardi

    10/13/2019, 1:44 AM
    Is there any reason not to use
    Dispatchers.Main.immediate
    on Android?
    a
    m
    +2
    19 replies · 5 participants
  • n

    napperley

    10/14/2019, 2:41 AM
    Keep on getting a
    NoSuchMethodError
    when running a program that uses a Kotlin library I have developed called KMQTT Client ( https://gitlab.com/napperley/kmqtt-client ), which uses coroutines. The error occurs when invoking the
    publish
    function. Below is the function's definition ( https://gitlab.com/napperley/kmqtt-client/blob/master/src/jvmMain/kotlin/org/digieng/kmqtt/client/MqttClient.kt#L37 ) in the library:
    actual suspend fun publish(topic: String, msg: MqttMessage, timeout: Long): MqttError? = try {
            client.publish(topic, PahoMqttMessage(msg.payload.toByteArray()))
            null
        } catch (mqttPersistenceEx: MqttPersistenceException) {
            MqttError(mqttPersistenceEx.message ?: "Message persistence failed.", MqttStatus.MSG_PERSISTENCE_FAILED)
        } catch (mqttEx: MqttException) {
            MqttError(mqttEx.message ?: "Message delivery failed.", MqttStatus.MSG_DELIVERY_FAILED)
        }
    Below are some of the error details:
    Exception in thread "main" java.lang.NoSuchMethodError: 'java.lang.Object org.digieng.kmqtt.client.MqttClient.publish$default(org.digieng.kmqtt.client.MqttClient, java.lang.String, org.digieng.kmqtt.client.MqttMessage, long, kotlin.coroutines.Continuation, int, java.lang.Object)'
    1 reply · 1 participant
  • a

    Alexjok

    10/15/2019, 8:14 AM
    Hello, wich way is better for run global coroutine? And do we have another opportunity to GlobalScope.launch?
    g
    z
    4 replies · 3 participants
  • m

    myanmarking

    10/15/2019, 2:50 PM
    mainScope.launch{
    	
    			onDateChanged // conflatedBroadcastChannel
                    .asFlow()
                    .distinctUntilChanged()
                    .collect{ ... }
    
                onTimeChanged // conflatedBroadcastChannel
                    .asFlow()
                    .distinctUntilChanged()
                    .collect{ ... }
    }
    j
    v
    6 replies · 3 participants
  • t

    Tristan Caron

    10/15/2019, 4:47 PM
    Hello, I have been reading about DataFlow (or whatever it will be called). And I was wondering. Once it will be delivered, what use cases will be left for Channels?
    g
    2 replies · 2 participants
  • c

    Casey Brooks

    10/15/2019, 7:26 PM
    Is there anything out there for repeatedly reading input from stdin, something like a suspending version of
    readLine()
    in a while loop?
    t
    z
    +1
    9 replies · 4 participants
  • r

    Rohan Maity

    10/16/2019, 4:17 AM
    What is use case of coroutines flow ? What does it provide ?
    z
    g
    +1
    9 replies · 4 participants
  • t

    Tsvetozar Bonev

    10/16/2019, 10:50 AM
    I'm trying to run a few http calls asynchronously with coroutines but I'm having trouble retrieving the final result, as I cannot await outside of the scope. Do I need to use runBlocking or does it only serve a purpose in tests
    d
    1 reply · 2 participants
  • d

    Dominaezzz

    10/16/2019, 10:51 AM
    I have state I want to share between
    onStart
    and
    onCompletion
    of a
    Flow
    . (Basically open a resource in
    onStart
    and close it in
    onCompletion
    ) What's the most idiomatic way besides reinventing the wheel?
    g
    e
    +1
    7 replies · 4 participants
  • p

    Pablichjenkov

    10/16/2019, 4:00 PM
    Philosophical Question: Recently while talking about Coroutines with a colleague he asked what is
    suspend
    . My naive response was:
    Basically, if you declare a function `suspend`, when this function gets called, its actual invocation is placed in a Queue of Jobs to be executed in some Dispatcher. 
    If the Dispatcher Thread happen to be the same as the calling Thread, it may be possible that the invocation happens immediately in the same running loop.
    After the *suspending function* executes free of exceptions, then code will resume at the line right after the function call site.
    Then he replied: What happened to the original Thread that called the
    suspending function
    . Then I said:
    The calling Dispatcher Thread returns at the calling site. When the *suspend function* is over the Continuation mechanics make sure it resumes in the same caller Dispatcher, not necessarily the same caller Thread but the same caller Dispatcher
    Is anything terribly misleading in my brief summary of suspension?
    s
    u
    3 replies · 3 participants
  • n

    napperley

    10/17/2019, 3:24 AM
    Keep on getting this error which is reproducible:
    Exception in thread "main" java.lang.NoSuchMethodError: org.digieng.kmqtt.client.MqttClient.connect$default(Lorg/digieng/kmqtt/client/MqttClient;Lorg/digieng/kmqtt/client/MqttConnectionOptions;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object;
    	at org.example.mqtt_test.MainKt$main$1.invokeSuspend(main.kt:11)
    	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    	at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
    	at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:270)
    	at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:79)
    	at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:54)
    	at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
    	at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:36)
    	at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
    	at org.example.mqtt_test.MainKt.main(main.kt:8)
    	at org.example.mqtt_test.MainKt.main(main.kt)
    Which Issue Tracker should I use for creating the issue (Kotlin or KotlinX Coroutines)?
    l
    v
    11 replies · 3 participants
  • a

    alexfacciorusso

    10/18/2019, 10:37 AM
    This is something I came up:
    private val _state = liveData<LoginViewState> {
            coroutineScope {
                launch {
                    usernamePasswordChannel.consumeEach { (username, password) ->
                        validateLoginDataUseCase.validateLoginData(
                            username,
                            password
                        ).perform(latestValue!!).also { emit(it) }
                    }
                }
                launch {
                    isLoggingInChannel.consumeEach {
                        usernamePasswordChannel.value.let { (username, password) ->
                            performLoginUseCase.login(
                                username,
                                password
                            )
                        }.perform(latestValue!!).also { emit(it) }
                    }
                }
            }
        }
    It looks a bit odd, has anyone any suggestion about something I’m misusing or that can be optimised in terms of code?
    m
    d
    +1
    10 replies · 4 participants
  • s

    Sujit

    10/18/2019, 5:11 PM
    I'm getting quite stuck with coroutines in one particular unit test, that only occur once in a while leading to only occasional failed test with error message:
    Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used
    . I do have the following in my unit tests:
    @ObsoleteCoroutinesApi
        private lateinit var mainThreadSurrogate: ExecutorCoroutineDispatcher
    
        @ObsoleteCoroutinesApi
        @ExperimentalCoroutinesApi
        @Before
        fun before() {
            mainThreadSurrogate = newSingleThreadContext("UI thread")
            Dispatchers.setMain(mainThreadSurrogate)
        }
    
        @ObsoleteCoroutinesApi
        @ExperimentalCoroutinesApi
        @After
        fun tearDown() {
            Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
            mainThreadSurrogate.close()
        }
    This only happens on one of many unit tests in the same class, which is in this place: https://github.com/UrbanCompass/Snail-Kotlin/blob/master/snail-kotlin/src/test/java/com/compass/snail/ObservableTests.kt#L221 I'm making this into a kotlin multiplatform project, and running unit tests through the
    androidTest
    . Any pointers on this please?
    z
    l
    18 replies · 3 participants
Powered by Linen
Title
s

Sujit

10/18/2019, 5:11 PM
I'm getting quite stuck with coroutines in one particular unit test, that only occur once in a while leading to only occasional failed test with error message:
Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used
. I do have the following in my unit tests:
@ObsoleteCoroutinesApi
    private lateinit var mainThreadSurrogate: ExecutorCoroutineDispatcher

    @ObsoleteCoroutinesApi
    @ExperimentalCoroutinesApi
    @Before
    fun before() {
        mainThreadSurrogate = newSingleThreadContext("UI thread")
        Dispatchers.setMain(mainThreadSurrogate)
    }

    @ObsoleteCoroutinesApi
    @ExperimentalCoroutinesApi
    @After
    fun tearDown() {
        Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
        mainThreadSurrogate.close()
    }
This only happens on one of many unit tests in the same class, which is in this place: https://github.com/UrbanCompass/Snail-Kotlin/blob/master/snail-kotlin/src/test/java/com/compass/snail/ObservableTests.kt#L221 I'm making this into a kotlin multiplatform project, and running unit tests through the
androidTest
. Any pointers on this please?
z

zak.taccardi

10/18/2019, 5:12 PM
inject your dispatchers
or better, inject your
CoroutineScope
then use either the scope provided from
runBlocking { }
or
runBlockingTest { }
for unit tests
s

Sujit

10/18/2019, 5:13 PM
Yeah, I do inject the dispatcher in the KMP version of that source code, which looks like this:
observable.debounce(Dispatchers.Default, delayMs = delayMs).subscribe(Dispatchers.Default, next = {
            received.add(it)
        })
Actually I was using
Dispatchers.Main
before
z

zak.taccardi

10/18/2019, 5:14 PM
No, I mean you should never refer to `Dispatchers.Main`/`Dispatchers.Default`/`Dispatchers.IO` in any class you care about unit testing
☝️ 1
l

louiscad

10/18/2019, 5:14 PM
Looks like a race condition where some code is run at class initialization, before the
@Before
annotated function.
👍 1
z

zak.taccardi

10/18/2019, 5:14 PM
it’s a static reference
s

Sujit

10/18/2019, 5:16 PM
Huh. I do have the initialization of the
Dispatchers
reference initialized in a different class, that gets injected to the class I'm testing. Is that not the way to do Coroutines
Also, I don;t think there is any initialization before the
@Before
annotation here. Here's what I've in setup:
private lateinit var subject: Observable<String>
    private lateinit var strings: MutableList<String>
    private var error: Throwable? = null
    private var done: Boolean? = null

    @ObsoleteCoroutinesApi
    private lateinit var mainThreadSurrogate: ExecutorCoroutineDispatcher

    @ObsoleteCoroutinesApi
    @ExperimentalCoroutinesApi
    @Before
    fun before() {
        runBlockingTest {
            mainThreadSurrogate = newSingleThreadContext("UI thread")
            Dispatchers.setMain(mainThreadSurrogate)
            subject = Observable()
            strings = mutableListOf()
            error = null
            done = null
            subject.subscribe(Dispatchers.Unconfined,
                next = { strings.add(it) },
                error = { error = it },
                done = { done = true }
            )
        }
    }
Also, updated to run that unit test in
runBlocking{}
scope, that throws out the same error. Sometimes, the test case, pass, but that error message of using
setMain
still shows up in the log
Think I got it now. No more errors and warnings after using
TestCoroutineDispatcher()
instead of
newSingleThreadContext
😒imple_smile:
👍 1
z

zak.taccardi

10/18/2019, 6:27 PM
referring to a static dispatcher is an anti-pattern
s

Sujit

10/18/2019, 6:28 PM
Ahh, I think I see what you are saying now @zak.taccardi!
👍 1
z

zak.taccardi

10/18/2019, 6:29 PM
it just makes testing much more difficult. We have an interface lik
interface AppDispatchers {
    val main: CoroutineContext get() = Dispatchers.Main
    val default: CoroutineContext get() = Dispatchers.Default
    val io: CoroutineContext get() = <http://Dispatchers.IO|Dispatchers.IO>
}
This allows for easy testing
s

Sujit

10/18/2019, 6:30 PM
Yeah, that's the pattern I'm looking to implement now. Makes much more cleaner.
z

zak.taccardi

10/18/2019, 6:32 PM
For example, idk if you are Android, but you can then create an
EspressoDispatchers()
fun EspressoDispatchers() : AppDispatchers = object : AppDispatchers {
    override val default = AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()
    override val io = AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()
}
and definitely inject your
CoroutineScope
View count: 3