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

    Robert Jaros

    02/13/2021, 1:28 AM
    Is it possible to get
    MutableStateFlow<S>
    from
    MutableStateFlow<S?>
    ?
    i
    d
    z
    • 4
    • 8
  • w

    WukongRework.exe

    02/13/2021, 5:02 AM
    i was messing around with the
    withTimeout
    function and found that if I put a loop, it does not trigger the timeout cancellation exception but if I use a delay statement for the same amount of time, then it triggers the catch block. Could anyone explain why?
    Untitled
    j
    z
    • 3
    • 4
  • a

    Alex Vasilkov

    02/14/2021, 7:25 AM
    Mutex vs StateFlow (sounds strange, but please read on) Suppose you need to synchronize few suspending calls (e.g. DB reads and DB writes) so that only one action is running at a time. You cannot use java synchronization or reentrant lock as it does not correctly work with suspension (https://blog.danlew.net/2020/01/28/coroutines-and-java-synchronization-dont-mix/). It seems like the only suitable option is to use
    Mutex
    , but it is very slow, if you’ll run the examples from https://kotlinlang.org/docs/shared-mutable-state-and-concurrency.html you’ll notice that
    Mutex
    is like 100 times slower than atomics. I found a way to use
    MutableStateFlow<Boolean>
    for suspending calls synchronization and it seems to be 5-10 times faster than
    Mutex
    , I’m not sure if there are any hidden gotchas with this approach though (see more in the thread).
    ✅ 1
    👀 1
    i
    d
    +3
    • 6
    • 45
  • n

    Nick Williams

    02/14/2021, 2:45 PM
    I know Flow<T>.combineLatest is deprecated as it is just called combine but is there a true combineLatest (in the same vain as transformLatest, collectLatest, mapLatest, flatMapLatest) or does combine already behave this way (I don't believe so because the docs don't mention it)
    a
    w
    • 3
    • 4
  • w

    Will Mwendwa

    02/15/2021, 6:55 AM
    Hello guys, I'm asking if anyone knows a good website to learn about coroutines
    a
    l
    +2
    • 5
    • 7
  • s

    Sergey Skaredov

    02/15/2021, 3:07 PM
    hi! is there a way to convert Flow<ByteArray> to single InputStream, but without storing all emitted bytes in memory?
    l
    u
    • 3
    • 4
  • a

    adambl4

    02/16/2021, 7:22 AM
    Hey, I have a buffered channel with max capacity let’s say 10 and BufferOverflow.SUSPEND, and I want to let sender to send new values to channel only when there are 5 items left in the buffer, not immediately when buffer changed from 10 to 9. Is there a way to check the number of buffered items on the sender side? Thanks.
    z
    e
    • 3
    • 2
  • w

    Will Mwendwa

    02/16/2021, 9:40 AM
    Currently doing a tutorial but when I run this code from the tutorial it runs an error can anyone help
    w
    • 2
    • 5
  • p

    Pablo

    02/16/2021, 4:02 PM
    Hello if my presenter is written in java and my datasource is in kotlin and I have used coroutines, how do I connect them? Do I have to use the
    suspendCancelableCoroutine{..}
    ? Then do i need the
    launch{}
    somewhere? Or from the java class I call the method of my presenter and that's it? I can avoid the launch?
    d
    • 2
    • 4
  • b

    Ben Madore

    02/16/2021, 6:57 PM
    I’m building a spring boot web app that receives “events” via HTTP requests, and does some processing then sends them to AWS EventBridge (serverless message bus). These events are “fire and forget” from the producer side, so my app immediately returns a response to the HTTP message. I’ve got it working as such right now, but the IO to call the AWS service seems to slow down. I’d like to batch up multiple Events into a single call to the AWS service. i.e. 5 separate inbound http requests containing Event1-Event5 result in a single outbound request to AWS. Is BufferedChannels the appropriate abstraction for this?
    m
    • 2
    • 1
  • r

    rsetkus

    02/18/2021, 12:43 PM
    Hi. I'm writing unit tests for multiplatform project and getting inconsistent coroutines results for Kotlin Native. Perhaps this is not the best way to write tests but it is working for Android platform. Here is simplified version of my test: Test function:
    @Test
    fun testSuccess() = runBlocking {
        val repository = Repository()
        var actual: String? = null
    
        val job = repository.getData(TEST_URL) {      
            actual = it
        }
        job.join()
    
        assertEquals(TEST_MESSAGE, actual)
    }
    Repository getData function:
    fun getData(
        url: String,
        callback: (String) -> Unit = {}
    ): Job {
        return GlobalScope.launch(dispatcher) { // Dispatchers.Main (Android), NsQueueDispatcher (iOS)
            try {
                val message: String = httpClient.request(...)
                callback(message)
            } catch (e: Exception) {
                println("Exception: $e")
            }
        }
    }
    Test passes running for Android platform but getting infinite loop for iOS platform. Does anybody know a good way to test a callback function which was invoked within coroutine? Any help much appreciated. 🙏🏻
    u
    • 2
    • 27
  • b

    Bradleycorn

    02/18/2021, 4:36 PM
    HI all ... basic question, as I'm still fairly new to coroutines ... I've setup a
    SimplePoller
    class that will run a
    block: suspend () -> Unit
    on a given interval. it looks like this (code condensed a bit for posting in Slack):
    class SimplePoller(private val interval: Long, private val block: suspend () -> Unit) {
    
        private var job: Job? = null
    
        fun start(scope: CoroutineScope) {
            if (job == null || job?.isCompleted == true) {
                job = scope.launch {
                    while (isActive) {
                        try {
                            block()
                            delay(interval)
                        } catch (ex: Exception) { cancel() } // stop on errors
                    }
                }
            }
        }
    
        fun stop() {
            job?.let { if (it.isActive) it.cancel() }
        }
    }
    Most of the time, it's used to poll the
    block
    while some Android
    Lifecycle
    is in a certain state. For example:
    val myPoller = SimplePoller(60_000) {
        //do some work that needs to be repeated like call a network api, etc
    }
    
    lifecycleScope.launch { 
        whenResumed { 
            myPoller.start(this)    
        }
    }
    Inside the poller, I launch a new job in the passed in scope so that I can "manually" (via a call to
    stop()
    ) stop the polling if necessary. Does this seem like a good approach? It seems to work pretty well. In testing the poller runs while the lifecycle is resumed, and suspends (because the passed in scope uses a magical Android "PausingDispatcher") when lifecycle < resumed. It also seems flexible enough that I could really use it in other, non-android-lifecycle situations:
    someScope.launch {
       myPoller.start(this)
    }
    
    // And then sometime later:
    myPoller.stop()
    I don't see anything immediately wrong, but as I mentioned, I'm still new to coroutines, so... 🤷
    a
    u
    • 3
    • 12
  • f

    Florian

    02/18/2021, 4:47 PM
    if I call
    lauch
    inside a
    channelFlow
    , what coroutine scope is used for that
    channelFlow
    ? The one that collects from the
    channelFlow
    ?
    l
    • 2
    • 2
  • z

    zak.taccardi

    02/18/2021, 7:57 PM
    Are there any coroutine bindings for
    Service
    in Android? We’re currently using
    override fun onHandleWork(intent: Intent)
    in a
    JobIntentService
    and I was wondering if there was a more idiomatic way to make that function Coroutine friendly, as opposed to using
    runBlocking { }
    in there
    l
    i
    +2
    • 5
    • 5
  • c

    Ciprian Grigor

    02/18/2021, 8:41 PM
    Are there any issues in using Flow (MutableStateFlow) with databinding?
    g
    • 2
    • 2
  • a

    Andrew Ebling

    02/19/2021, 9:52 AM
    I’m new to coroutines and struggling to get my head around the conceptuals while trying to implement a debounce:
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when(item.itemId) {
            R.id.refresh -> {
                flow {
                    callbacks?.refreshAllTheThings()
                }.debounce(5000)
                return true
            }
            else -> {
                return super.onOptionsItemSelected(item)
            }
        }
    }
    ...however I get the following compilation error:
    Not enough information to infer type variable T
    I’ve gone and looked at the implementation of
    debounce()
    but the examples in the comments suggest what I have above should be sufficient. Why does flow need type information if I just want to execute one line of code, at most, every 5 seconds?
    w
    • 2
    • 13
  • s

    spierce7

    02/19/2021, 6:01 PM
    Is StateFlow acceptable to use for short running operations where I need a flow of data? State flows don’t complete, so the collection of them doesn’t stop right?
    m
    c
    k
    • 4
    • 15
  • r

    rocketraman

    02/19/2021, 7:54 PM
    With
    StateFlow
    , is it safe to access the current state inside a
    catch
    block?
    :yes: 1
    l
    • 2
    • 1
  • s

    samuel

    02/19/2021, 11:09 PM
    Hi, I’m experimenting with state flow to see if i can get some sort of reactive stack implementation. My idea is that i have a  class that holds the state, which only one subscriber observes, but multiple classes can update the state. This is what i have so far (in 🧵), but i have some strange behaviour. Calling 
    replaceState
     works as expected with the subscriber getting the new value, however, calling 
    updateState
     doesn’t. Does any one have a clue why this happens?
    d
    m
    • 3
    • 7
  • d

    Dominaezzz

    02/20/2021, 2:38 PM
    I'm writing a suspend function but it's not safe to call concurrently. Usually one would call this method "Not thread safe" but in the coroutine world what do you call this? "Not coroutine safe"? Sounds weird.
    l
    a
    +5
    • 8
    • 21
  • r

    Ran

    02/21/2021, 3:24 AM
    Hey, guys,. There is a problem about kotlin coroutine. I used
    kotlinx-coroutines-test
    library to test my coroutines code. But after I used
    TestCoroutineDispatcher
    to mock the dispatcher, the coroutine resumed continually until throw an exception with the message:
    kotlinx.coroutines.CoroutinesInternalError: Fatal exception in coroutines machinery for DispatchedContinuation[TestCoroutineDispatcher[currentTime=0ms, queued=0], Continuation at xxx.viewmodel.CarListViewModel$loadCars$1.invokeSuspend(CarListViewModel.kt)@1da6ee17]. Please read KDoc to 'handleFatalException' method and report this incident to maintainers
    You can find the specific code at https://youtrack.jetbrains.com/issue/KT-45088.
    l
    • 2
    • 2
  • d

    darkmoon_uk

    02/21/2021, 4:40 AM
    How can I create a single threaded Dispatcher on Kotlin Native for iOS (that isn't the Main Dispatcher)? I want to keep business logic off the Main thread but also not worry about state being frozen between threads, which is a pitfall when using the Default Dispatcher (on a multi core device). A two-threaded delineation between UI/business logic seems like a more manageable, pragmatic middle ground for KMM projects until the new Native Memory model changes the landscape.
    m
    • 2
    • 7
  • s

    Stylianos Gakis

    02/21/2021, 9:47 PM
    I was watching this talk by Elizarov about coroutines (Kotlin Conf 2018), where a downloading example was given. In this post, he explained some problem that existed with a deadlock, and a solution in a 2019 post here. However in this last post, there is a note about how Channels should be considered a "low level primitive" suggesting that flows(?) may be a better alternative. Now my question is, is this example code still considered the optimal way that one would solve this downloader problem, or should the entire channel process optimally be replaced with a different implementation without raw Channels? If so, is there an update on this problem, perhaps by Elizarov himself on how this would be solved with the state of coroutines as of right now? It would be really interesting to see the differences in order to also understand better what problems these new constructs can solve easier than raw channels.
    👍 2
    l
    • 2
    • 1
  • c

    CLOVIS

    02/22/2021, 3:53 PM
    Would it be correct to say that this code:
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
      foo()
    }
    is conceptually equivalent as this one:
    launch(<http://Dispatchers.IO|Dispatchers.IO>) {
      foo()
    }.join()
    Since the implementation is very different, I expect that for performance reasons it does something else, but as a developer should I use
    withContext
    as syntax sugar for
    launch().join()
    , or is there something else I need to know about?
    l
    s
    • 3
    • 6
  • i

    Ivan

    02/23/2021, 7:17 AM
    Hi folks. I need to retrive information from coroutine context (ktor logged user) in an implementation of a function from an abstract java class provided by an external library. I can't implement this function as a suspend function and so i can't access to the coroutine context. Do you have any suggestion?
    n
    t
    • 3
    • 14
  • l

    Lucien Guimaraes

    02/23/2021, 12:40 PM
    Hello 👋 I have a question regarding Unit Test and Flow. I'm following the Testing flows Android documentation to test my work. But I'm stuck with the following error
    This job has not completed yet
    Here is my implementation:
    class MyUseCaseImpl(
        myRepository: MyRepository,
        myID: String,
        ioDispatcher: CoroutineDispatcher,
    ) : MyUseCase {
    
        override val state = MutableStateFlow<MyState>(MyState.Loading)
    
        init {
            CoroutineScope(ioDispatcher).launch {
                myRepository
                    .requestStuff(myID)
                    .map { MyState.Success(it) }
                    .catch { state.emit(MyState.Error(it)) }
                    .collect { state.emit(it) }
            }
        }
    }
    
    interface MyUseCase {
    
        sealed class MyState {
            object Loading: MyState()
            data class Error(val throwable: Throwable) : MyState()
            data class Success(val hikeTrack: HikeTrackResponse) : MyState()
        }
    
        val state: Flow<MyState>
    }
    And here is the UT failing:
    ...
    private val coroutineDispatcher = TestCoroutineDispatcher()
    ...
    @Test
        fun `Given ... `() = coroutineDispatcher.runBlockingTest {
    
        When calling myRepository.requestStuff(myID) `it returns` flowOf(stuffResponse)
    
        val myUseCase = MyUseCase(
            myRepository,
            myID,
            coroutineDispatcher,
        )
    
        myUseCase.state.take(2).toList() shouldBeEqualTo listOf(
            MyState.Loading,
            MyState.Success(stuffResponse),
        )
      }
    }
    From the documentation it says
    If the test needs to check multiple values, calling toList() causes the flow to wait for the source to emit all its values and then returns those values as a list. Note that this works only for finite data streams
    . For what I understand, the UT fails because the flow I'm returning to my repository is an infinite streams. But shouldn't
    flowOf(value)
    create a finite stream ? Thanks !
    ✅ 1
    a
    • 2
    • 30
  • m

    Michal Klimczak

    02/23/2021, 7:12 PM
    Can multiple different threads 'join' the same Job? I have a library which expects blocking calls to some 'authenticate' method. This method will then be called from multiple threads and invoke a 'refreshToken' suspend function (which has to be invoked in runBlocking because 'authenticate' is expected to be blocking) but if some of these calls are called simultaneously I only want the 'refreshToken' to be called once for all of of them. My idea is to create a Job when the first one hits and them all the other could join this Job if it still exists. Is it a good approach or is there a better way?
    z
    w
    u
    • 4
    • 32
  • u

    ursus

    02/24/2021, 5:46 AM
    Is
    Mutex
    suitable to be used at business logic level for example in
    sendChatMessage()
    to keep them sequential?
    g
    • 2
    • 4
  • t

    Thiago

    02/24/2021, 3:35 PM
    Hy folks, I'm using
    receiveAsFlow
    to transform a Channel in Flow. After cancel the CoroutineScope where I'm collecting the Channel values it seems not have closed the Channel. Can be codes like below create leaks without call
    close()
    ? Should I add a call to
    invokeOnCompletion
    to make sure that close my Channel as:
    invokeOnCompletion {
                channel.close()
            }
    channel_to_flow.kt
    t
    • 2
    • 1
  • k

    Kshitij Patil

    02/25/2021, 9:52 AM
    what’s the difference between applying
    conflate
    on
    Flow<T>
    and using
    StateFlow<T>
    ? Also, why can’t I just get a
    StateFlow
    when I use
    map
    on existing
    StateFlow
    ?
    s
    z
    • 3
    • 4
Powered by Linen
Title
k

Kshitij Patil

02/25/2021, 9:52 AM
what’s the difference between applying
conflate
on
Flow<T>
and using
StateFlow<T>
? Also, why can’t I just get a
StateFlow
when I use
map
on existing
StateFlow
?
s

streetsofboston

02/25/2021, 12:55 PM
Because map is already defined on a Flow and there it returns another Flow. A StateFlow is Flow, and since we don't want to change the api of Flow, that means that map on a StateFlow must return a Flow as well. You can create an extension method called something like mapWithState on a StateFlow to do what you want.
z

Zach Klippenstein (he/him) [MOD]

02/25/2021, 4:02 PM
Roman explained why
map
on
StateFlow
doesn’t make sense here
k

Kshitij Patil

02/25/2021, 6:06 PM
I do have the exact same use case you mentioned in the First comment there. Is there any problem with the approach you shared ? IE,
state.map{ }.stateIn(scope)
?
z

Zach Klippenstein (he/him) [MOD]

02/25/2021, 6:15 PM
No problem with it, as long as you have a scope
View count: 13