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

    Jan

    07/31/2021, 11:53 PM
    I have a little problem with https://github.com/TooTallNate/Java-WebSocket and Kotlin Coroutines (Client). If I disconnect, I want to reconnect again. I can't just do that in <MyClient>.onClose because that's on the websocket thread. I want to fix that with coroutines but just <Scope>.launch { reconnect() } doesn't work because the program closes (probably non-blocking). Any ideas?
    t
    2 replies · 2 participants
  • m

    marcinmoskala

    08/02/2021, 8:06 AM
    When coroutines was still young, there was a folder showing a different use-cases of the suspending functions, like making something similar to Goroutines and other. Anyone knows where is it now?
    g
    1 reply · 2 participants
  • a

    Anoop Gopalakrishnan

    08/02/2021, 10:12 PM
    Hi I am trying to run a multiple jobs in a loop exactly three jobs. And I am using supervisor job because I don't want to cancel other jobs if any one fails. It's working fine. But when I am trying to test this using Mockk, I am not able to provide answers for the suspend functions, because there is additional argument continuation been added to suspend functions under the hood. I am using coEvery and coVerify to check the calls. Did anyone came across this. ?
    e
    4 replies · 2 participants
  • j

    juan torres

    08/03/2021, 7:11 AM
    Hello everyone 👋 I’m wondering if there is any merit or risks in combining
    async
    and
    withContext(<http://Dispatches.IO|Dispatches.IO>)
    to be able to execute blocking code, in particular making multiple IO calls with Spring RestTemplate, in an asynchronous fashion like so:
    fun <T> CoroutineScope.myRestTemplateAsync(
        context: CoroutineContext = EmptyCoroutineContext,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        block: suspend CoroutineScope.() -> T
    ): Deferred<T> {
        return async(context, start) {
            withContext(<http://Dispatchers.IO|Dispatchers.IO>) { block() }
        }
    }
    The full description, observations, and code samples are in this SO Post
    k
    3 replies · 2 participants
  • p

    pgreze

    08/03/2021, 9:00 AM
    Hi there! I’m working on an open source library I released few months ago to easily launch external process from Kotlin: https://github.com/pgreze/kotlin-process/pull/7 I would like to add cancellation support but the way I found so far seems not covering all cases (see PR description). For example, is it worth having a third async operation actively monitoring the isActive state? Thank you in advance for any support 🙏
    e
    n
    11 replies · 3 participants
  • n

    natario1

    08/03/2021, 1:44 PM
    What's the best way to combine a
    Flow<State>
    that represents some state and a
    Channel<Event>
    ? Regular combine(...) does not work well, because the event should only be processed once (against the most recent state). I currently achieve this with a pretty complex channelFlow { } with two coroutines and saving stuff in local `var`s, but I wonder if there's a smarter way.
    d
    n
    15 replies · 3 participants
  • g

    Glen

    08/03/2021, 8:39 PM
    Hello everyone. I am trying to modify a library in order for it to use coroutines, but I want the user-facing function to be called without having to be aware about coroutines. Code can be found here: https://github.com/AnonymousGeekDev/JP2ForAndroid/blob/kotlin-develop/library/src/main/java/com/gemalto/jp2/JP2Decoder.kt#L227 Any help/insight appreciated.
    c
    n
    10 replies · 3 participants
  • a

    andylamax

    08/04/2021, 1:16 AM
    Are there any technical limitations that makes the coroutines library not to target linuxArm64, linuxArm32Hfp, and mipsel targets? If there aren't, Why doesn't the library target those platforms? If there are, What are the limitations?
    e
    t
    4 replies · 3 participants
  • m

    muthuraj

    08/04/2021, 7:58 AM
    Does anyone know how to unit test code which uses
    Flow.debounce
    ? The unit test doesn't wait until debounce is completed. It should actually advance the delay since I'm using
    runBlockingTest
    as per the documentation, but that doesn't happen. Here is an example that reproduces my case.
    class DebounceTest(scope: CoroutineScope) {
        private val stateFlow = MutableStateFlow("")
        val resultFlow = MutableStateFlow("")
    
        init {
            stateFlow.debounce(500)
                .onEach {
                    resultFlow.value = it
                }
                .launchIn(scope)
        }
    
        fun search(text: String){
            stateFlow.value = text
        }
    }
    
    @Test
        fun debounceTest() = runBlockingTest {
            val sut = DebounceTest(this)
            sut.search("test")
            assertThat(sut.resultFlow.value).isEqualTo("test")
        }
    The test here fails saying the actual value of
    resultFlow.value
    is empty string instead of
    test
    m
    n
    4 replies · 3 participants
  • d

    Daniele Segato

    08/04/2021, 7:59 AM
    I need to unit test concurrent calls
    runBlockingTest {
      val mutex = Mutex(true)
      val mockedApi = mock<MyApi> {
        onBlocking { invoke() } doSuspendableAnswer {
          mutex.withLock {
            // wait unlock to run
          }
        }
      }
      val sut = MyTestedClass(
        api = mockedApi,
      )
    
      println("async callA"}
      val callA = async { sut.doCall() }
      println("async callB"}
      val callB = async { sut.doCall() }
    
      mutex.unlock()
      // ....
    }
    this test never completes, it runs forever and stop at
    async callA
    the
    async callB
    is NEVER printed the
    MyTestedClass
    class MyTestedClass(private val api: MyApi) {
      fun doCall() { // this is NOT suspendable
        runBlocking {
          api() // but this is suspendable
        }
      }
    }
    Isn't async supposed to be non-blocking? I would expect callA and callB to be executed concurrently until they reach the mutex but apparently the first async is blocking in the test and stop at the mutex blocking all the test. What am I missing here?
    m
    13 replies · 2 participants
  • j

    julioromano

    08/05/2021, 11:02 AM
    I have a suspend function which calls other 3 suspending functions. How can I have
    doSomething
    call the 3 suspending functions serially? (i.e. waiting for each one to complete before calling the other?)
    suspend fun doSomething() {
        suspendingFun1()
        suspendingFun2()
        suspendingFun3()
      }
    🧵
    r
    s
    +2
    11 replies · 5 participants
  • n

    napperley

    08/06/2021, 1:50 AM
    What is happening with getting KotlinX Coroutines to support the linuxArm32Hfp target? It is reaching a point where the long standing issue ( https://github.com/Kotlin/kotlinx.coroutines/issues/855 ) needs to be addressed. Some of the third party Coroutine libraries support the linuxArm32Hfp target but require the user to use a high level concurrency model, which isn't suitable for library authors and when developing certain types of applications.
    t
    2 replies · 2 participants
  • m

    Marty Pitt

    08/06/2021, 10:22 AM
    Hi all. We've recently moved a single-threaded blocking process across to coroutines and Flow<>. We're trying to profile performance, and understand the "cost" of coroutines, to see if there's ways we can optimize. (We're not satisified with our performance currently, and looking for areas to tune). Are there any tools that can help with visibility of this, and understanding what's going on?
    l
    a
    +1
    5 replies · 4 participants
  • p

    PHondogo

    08/07/2021, 12:36 PM
    Hello! Hi can i find out what dispatcher is using?
    z
    1 reply · 2 participants
  • m

    Marc Knaup

    08/07/2021, 10:16 PM
    The error message is confusing here as it’s not clear what’s happening. I guess the code is indeed incorrect? Then just the documentation could be improved a little.
    suspend fun main() {
        flow {
            flowOf(1).collectLatest { emit(it) }
        }.collect { println(it) }
    }
    IllegalStateException: Flow invariant is violated
    😒 1
    e
    6 replies · 2 participants
  • a

    Aaron Waller

    08/09/2021, 9:58 AM
    Can someone explain to me whats the difference between
    with(GlobalScope){ launch{} }
    and
    GlobalScope.launch{}
    ? All I can find is: "You can use
    with()
    in order to avoid the repetition of the
    GlobalScope
    receiver" but I don't really get it. Thanks in advance
    a
    m
    +1
    6 replies · 4 participants
  • s

    Stefan Oltmann

    08/09/2021, 11:03 AM
    In this FeedStore class I want to launch a new coroutine on Dispatchers.IO, but it's not available. Why? I want to load data not on the UI thread... https://github.com/Kotlin/kmm-production-sample/blob/master/shared/src/commonMain/kotlin/com/github/jetbrains/rssreader/app/FeedStore.kt
    ✅ 1
    b
    r
    2 replies · 3 participants
  • v

    Vivek Modi

    08/09/2021, 1:13 PM
    Hey I want to call
    api
    from
    object
    class. I am new in Coroutines. That API call should be executer concurrently and app's flow should not wait for result of that call. I tried some code, but i am not sure is it correct way of doing it or not. Also i got a error`Process: com.dimen.app, PID: 12496`
    android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1605)
    private fun setupLogout() {
        logoutButton.setOnClickListener {
            LoginHelper.logout()
        }
    }
    fun logout() {
        logD("logout")
        deleteSession()
        .... more function
    } 
    private fun deleteSession() {
        runBlocking {
            Tokenclass.getToken()?.let {
                logE("token ::-> $it")
                apiCall.deleteSession(it).execute()
            }
        }
    }
    u
    n
    3 replies · 3 participants
  • s

    Slackbot

    08/09/2021, 7:26 PM
    This message was deleted.
    r
    1 reply · 2 participants
  • r

    Rob

    08/10/2021, 8:32 PM
    How do I run two coroutines concurrently but take the result of the first one that returns and cancel the other? Preferably a one liner.
    l
    e
    +5
    53 replies · 8 participants
  • e

    eygraber

    08/11/2021, 4:28 AM
    I have a wrapper class for CoroutineDispatcher that I use so that for tests I can provide test dispatchers:
    interface MyDispatchers {
      val main: CoroutineDispatcher
      val io: CoroutineDispatcher
      val computation: CoroutineDispatcher
      val unconfined: CoroutineDispatcher
    }
    Instead of using
    Dispatchers.*
    I use one of the properties from `MyDispatchers`(which are set to the corresponding
    Dispatchers.*
    ) Is this necessary, or does the coroutines test artifact have a construct that allows you to use
    Dispatchers.*
    and control them during a test?
    :yes: 2
    e
    8 replies · 2 participants
  • r

    Richard Gomez

    08/11/2021, 7:14 PM
    Given the following example, how do I ensure
    expensiveLookup
    only executes once (for a given id) and subsequent executions receive the cached value?
    suspend fun expensiveLookup(id: String): ExpensiveResult {
      val cached = cache.get(id)
      if (cache != null) {
        return cached
      }
    
      val result = // logic here
      
      cache.put(id, result)
      return result
    }
    This blog post from Doordash in 2018 has an interesting solution. Is there a 'better' way of doing this now? https://doordash.engineering/2018/08/03/avoiding-cache-stampede-at-doordash/
    m
    t
    +1
    7 replies · 4 participants
  • j

    Jimmy Alvarez

    08/12/2021, 3:12 AM
    Hello guys, hope you are doing good. This questions is kind of beginner level but I’m trying to understand a lil how concurrency works in coroutines. In this example i want to lunch 2 coroutines concurrently like this:
    coroutineScope.launch {
       // some work 
    }
    
    coroutineScope.launch {
       // some other work 
    }
    In my understanding, this should not block the thread given i’m launching both coroutines concurrently. but what is happening is that first coroutine blocks the thread so the second coroutine never gets executed. The only way I could make it run concurrently was to wrap
    // Some work
    into a
    suspend
    function, then I got the concurrent execution Could you explain a little why this only work by using the suspend function inside coroutine?
    a
    3 replies · 2 participants
  • l

    Lefko

    08/12/2021, 8:22 AM
    I'm getting crashes from unhandled exceptions from this code (see in thread) but don't understand why since it's surrounded by try/catch. Specifically I'm seeing
    java.lang.IllegalArgumentException: userUUID must not be empty
    1 reply · 1 participant
  • c

    corneil

    08/12/2021, 11:17 AM
    How about?
    wainting-ui.kt
    k
    1 reply · 2 participants
  • c

    christophsturm

    08/12/2021, 2:00 PM
    does it make sense to use -native-mt versions of coroutines also on the jvm? they show up as newer version so i could just update instead of marking the update as ignored
    l
    1 reply · 2 participants
  • b

    Brendan Campbell-hartzell

    08/13/2021, 4:54 AM
    I'm trying to test that my code correctly responds if a launched coroutine fails, but the failure in the coroutine causes subsequent tests to fail due to a "Delayed Exception." If I try to handle the exception in the test code, then the failure won't propagate to my prod code. I'm not sure how to catch an error from the prod code so that the tests aren't failing due to the intended test error. Any ideas? Code in thread.
    4 replies · 1 participant
  • k

    K Merle

    08/13/2021, 6:49 AM
    I am bit confused on what Coroutine flow should I take to replace LiveData. Flow, StateFlow, SharedFlow?
    a
    e
    +2
    9 replies · 5 participants
  • r

    ritesh

    08/13/2021, 8:31 PM
    Is there a difference between
    coroutineScope.coroutineContext.cancelChildren
    vs
    coroutineScope.cancel
    They both cancels all the childrens.
    d
    2 replies · 2 participants
  • e

    efemoney

    08/14/2021, 10:55 AM
    If I want to expose a “refreshable” flow as an input to my library, such that in addition to getting a stream of data, I as the library can also request for the latest data (as opposed to the latest cached data in the case of
    StateFlow
    ) … will this be a good way?
    interface RefreshableFlow: Flow (or SharedFlow or StateFlow) {
      fun refresh()
    }
    
    
    class RefreshableFlowImpl(val delegate: flow): Flow by flow, RefreshableFlow {
      override fun refresh() { ... } // launch coroutine/send event/etc that would eventually or not emit a new value
    }
    What are the pitfalls of doing something like this?
    e
    8 replies · 2 participants
Powered by Linen
Title
e

efemoney

08/14/2021, 10:55 AM
If I want to expose a “refreshable” flow as an input to my library, such that in addition to getting a stream of data, I as the library can also request for the latest data (as opposed to the latest cached data in the case of
StateFlow
) … will this be a good way?
interface RefreshableFlow: Flow (or SharedFlow or StateFlow) {
  fun refresh()
}


class RefreshableFlowImpl(val delegate: flow): Flow by flow, RefreshableFlow {
  override fun refresh() { ... } // launch coroutine/send event/etc that would eventually or not emit a new value
}
What are the pitfalls of doing something like this?
e

Erik

08/14/2021, 1:15 PM
I would just expose a StateFlow, from which the reader can collect (stream) or just read the latest value. Additionally, expose a refresh function that triggers the refresh mechanism, which will emit the latest value through the same state flow. Optionally, if you want that, you can make the refresh function also return that latest value. You will likely want to make the refresh function suspending too in that case.
e

efemoney

08/14/2021, 1:20 PM
The type in question is an input to my library. Consumers will provide a stream of data (via Flow and subtypes) and I, the library, will subscribe to this flow and also tell the consumer when to refresh/requery the data flow (in addition to whenever they think they should refresh/requery the flow) I’m just trying to see how to combine that under a single type and if the approach above makes sense.
e

Erik

08/14/2021, 1:22 PM
You can just make an interface with that state flow as a val and the refresh function. Your consumers will provide an instance of that interface to your lib
The contract is that consumers will have to implement the interface and that the refresh function behaves like you described
No need to complicate things by making a new flow subtype
(composition over inheritance)
e

efemoney

08/14/2021, 1:32 PM
Thanks @Erik. I could (and I have that currently) but now I need to know if the approach of subclassing also makes sense. Am I breaking any coroutine (concurrency, dispatching etc) rules? Will this work with all current flow operators? etc Also I don’t agree in this case that
interface X { val flow: Flow ; fun refresh() }
is (necessarily) a better API. For one at the callsite, it becomes
x.flow.collect { ... }
vs
x.collect { ... }
which may be less desirable depending on the concept
x
is meant to represent. Also for the same reason why (I imagine)
StateFlow
is not defined as
interface StateFlow<T> { val flow: Flow ; val value: T}
what I want is a “flow that can be refreshed” and not an “entitity that has a flow and can be refreshed”
e

Erik

08/14/2021, 1:34 PM
Take a look at the Flow, SharedFlow and StateFlow KDoc: are these interfaces stable for inheritance? If so, then go ahead with your approach. Otherwise use composition.
View count: 4