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

    zt

    08/24/2022, 3:57 AM
    I'm trying to use a websocket with ktor and I need to set up two while true loops. I've wrote this code which I thought would work but it only completes one iteration and then exits
    val eventJob = launch {
        while (true) {
            val event = try {
                when (val frame = incoming.receive()) {
                    is Frame.Text -> json.decodeFromString<Message.Event>(frame.readText())
                    is Frame.Close -> {
                        println("Received close frame: ${frame.readReason()}")
                        continue
                    }
                    else -> continue
                }
            } catch (e: Exception) {
                println("Error while receiving: ${e.message}")
                break
            }
            println("Received event: $event")
        }
    }
    
    val heartbeatJob = launch {
        while (true) {
            delay(helloMessage.data.heartbeatInterval.milliseconds)
            println("Sending heartbeat")
            sendSerialized(Message.Heartbeat)
        }
    }
    
    joinAll(eventJob, heartbeatJob)
  • v

    Vikas Singh

    08/24/2022, 9:13 AM
    Why does the below logic crashes where as if i separate the top-level it doesn't. val toplevel = CoroutineScope(Dispatchers.IO) this crashes: toplevel.launch { val sync = async { print("this is sync 1") throw RuntimeException() } try { sync.await() } catch (e: Exception) { print("Exception handled") } } This does not: val sync = toplevel.async { print("this is sync 1") throw RuntimeException() } toplevel.launch try { sync.await() } catch (e: Exception) { print("Exception handled") } }
    s
    5 replies · 2 participants
  • l

    Lukas Lechner

    08/24/2022, 11:27 AM
    Are there situations in which you, instead of using a suspend function, use a regular function that returns a Flow that emits a single value? Maybe to use some flow operators that make the code a bit cleaner?
    r
    s
    4 replies · 3 participants
  • p

    Pablo

    08/25/2022, 10:13 AM
    Hello is there any way to run two coroutines in parallel and then return the first result that finishes first? I've thought to use
    Job
    and then if the first finishes first cancel the second
    Job
    to stop doing the work, also I think the way to do it is using
    launch{}
    right? Instead of
    async {}
    s
    f
    +1
    10 replies · 4 participants
  • l

    Lukas Lechner

    08/25/2022, 1:30 PM
    The Coroutines docs discourage the use of
    flatMapMerge
    and
    flatMapConcat
    in regular application-specific flows, see attached image. What should we used instead when flatMapping two flows?
    t
    r
    7 replies · 3 participants
  • d

    Daniel Rodak

    08/26/2022, 1:32 PM
    Is it possible to start observation when launching
    StateFlow
    ? So the case is that I have
    StateFlow
    in my
    ViewModel
    and I would like to launch some observation(e.g. User status
    Flow
    ) but I would like to stop this observation at the same moment that I will stop observing main
    StateFlow
    itself so they need to be launched in the same scope. Currently I’m using combine with status observation flow but I’m ignoring events emitted by this Flow, is there a better way to handle it? Side not: I'm not using values emitted by the second flow directly so that's why I need to ignore them.
    s
    r
    3 replies · 3 participants
  • t

    turansky

    08/30/2022, 11:07 AM
    What is fine common name for Iterator-like interface, which has suspend
    hasNext
    ? ChannelIterator has similar contract
    t
    j
    +2
    8 replies · 5 participants
  • m

    Mark

    08/31/2022, 10:30 AM
    Is there something like
    combine
    but for when the flows (arguments) are calculated based on the item in the main flow? My use case is a flow of
    Item
    s where each
    Item
    has a number of properties whose values are provided by flows. Initially those properties are null and so the operator I’m trying to implement, would transform an
    Item
    such that the properties are populated and the resulting Flow will emit a new
    Item
    each time any of the properties updates (as well as when the original flow emits a new
    Item
    ).
    t
    r
    6 replies · 3 participants
  • t

    Tom Yuval

    08/31/2022, 12:00 PM
    Hi all, I’ve got multi-platform Kotlin code which uses coroutines, and it is important that things really execute in parallel. For my specific use case there is no real problem except for when targeting JavaScript, as that’s single-threaded and a coroutine has to actually be suspended in order for other things to execute. The solution I’m currently using is to call
    delay(1)
    in several places, to achieve just that: when any coroutine hits the
    delay(1)
    its execution is suspended, allowing others to run (and complete or hitting
    delay(1)
    themselves, allowing suspended coroutines to resume). And it generally seems to work. But it’s not elegant, and the delay itself, while not that noticeable, is not necessary. Is there another way to do it? Something I can do at certain places in the code to allow a coroutine to suspend execution just in order to allow others to run until they complete or do the same?
    c
    2 replies · 2 participants
  • o

    oday

    08/31/2022, 1:26 PM
    what’s the equivalent of a Completable? like if I have a method that just deletes thing and I don’t care what ends up happening with it, I just want to know if it’s done or not
    m
    s
    7 replies · 3 participants
  • t

    Tom Yuval

    08/31/2022, 1:56 PM
    I’m running some tests that call
    suspend
    functions, so I’m using
    kotlinx.coroutines.test.runTest
    . This has the useful feature of skipping `delay`s and simulating actual scheduling with virtual time, which is super useful as it allows the tests to run fast, and one can also control the order of execution of various parts of different coroutines very delicately. However, I have a very specific use case where functions under test use `delay`s, and I actually want the `delay`s to execute for real, just like they would in production (this shouldn’t normally be required in pure unit tests, but is necessary in my case as the functions I’m testing interact with other systems). Is there a way to do that?
    m
    e
    7 replies · 3 participants
  • c

    Colton Idle

    08/31/2022, 5:35 PM
    state.myList.forEachIndexed { index, it ->
      viewModelScope.launch {
        it.isDone.value = apiService.isDone(it.id)
      }
    }
    I thought I'd be able to add a
    .await()
    to the end of the launch block to know when all of those parrallel api calls are done, but that doesn't compile. Is there a more idiomatic way to do what I'm trying to do?
    m
    e
    +2
    40 replies · 5 participants
  • o

    oday

    08/31/2022, 6:46 PM
    how do I turn this code into coroutines? https://hastebin.com/ukuxatodew.kotlin I figured out that I am able to do this
    viewModelScope.launch(<http://dispatchers.io|dispatchers.io>) {
                val filterSources = try {
                    listOf(
                        launch { getLocation.execute() },
                        launch { getCategory.execute() },
                        launch { getPeriod.execute() },
                        launch { getDateRange.execute() }
                    ).joinAll().
                } catch (e: Throwable) {
    
                }
    
            }
    but unable to figure out how to get that to a map where i can use the stuff inside
    f
    36 replies · 2 participants
  • l

    Lilly

    09/01/2022, 11:27 AM
    I have a really specific use case and I guess I need something to pause and resume the emission of a flow multiple times. To be more concrete: I need to pause a flow to wait for a confirmation from another flow before emitting the next item. Any ideas how to solve this?
    j
    c
    +2
    10 replies · 5 participants
  • o

    oday

    09/01/2022, 1:15 PM
    how do I emulate the same behavior that Observable.combineLatest does? I have that inside a viewmodel and when I leave the screen and come back, that line is triggered again and fetches the values i’m requesting again if I just have viewModelSCope.Launch ( my stuff), it doesn’t get retriggered when coming back with new values
    n
    3 replies · 2 participants
  • n

    Nicolas Verinaud

    09/02/2022, 10:08 AM
    Hello ! Is it possible to unit test for job cancellation for a class like below ?
    class Sample(private val scope: CoroutineScope) {
        
        private var currentJob: Job? = null
        
        fun doSomeAsyncWork() {
            currentJob?.cancel() // how to test this line ?
            currentJob = scope.launch { 
                delay(5000)
            }
        }
    }
    m
    r
    6 replies · 3 participants
  • a

    Aditya Kurkure

    09/03/2022, 4:44 AM
    Is there an alternative to this https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-debug/ for android? We faced some issues with coroutines recently and the stack trace wasn't helpful so we were trying to explore to way to debug coroutines/ improve stack traces on android.
    r
    2 replies · 2 participants
  • z

    Zoltan Demant

    09/04/2022, 4:37 AM
    It seems to me that Im able to call a suspend function in a non-suspending block. Why is that? Details in thread 🧵
    e
    10 replies · 2 participants
  • d

    Dheeraj Singh Bhadoria

    09/04/2022, 10:05 AM
    coroutines runs in main thread how can i execute coroutines in background thread. ( Dispatchers.IO ) ?
  • d

    Dheeraj Singh Bhadoria

    09/04/2022, 10:10 AM
    suspend fun getTopKeys(con: Context, rootObject: JSONObject): MutableLiveData<AuthResponse> {
    
        return withContext(<http://Dispatchers.IO|Dispatchers.IO>){
            val gson = Gson()
    
            val accessToken = MyPrefConstant.getAccessToken(con)
    
            val retrofit = RetrofitConfig.getRetrofitWithAccessToken(accessToken, con)
    
            val service = retrofit?.create(ApiInterface::class.java)
    
            var data = AesKotlin.encrypt(rootObject!!.toString(),AppConfig.ENCRYPTION_KEY)
    
            Log.e("App1>>>>", data.replace("[\n]", "")!!.toString())
    
            val call = service?.getTopKeys(data.replace("[\n]", "")!!.toString())
    
            call?.enqueue(object : Callback<AuthResponse> {
                override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
    
                    if (response.code() == 200 && response.body().status.equals("OK")) {
                        val responseData = response.body()!!
                        searchData.value = gson.fromJson(gson.toJson(responseData), AuthResponse::class.java)
    
                        val i = Intent("return.apiResponse")
                        i.putExtra("data",  gson.toJson(responseData).toString())
                        i.putExtra("method", "getTopN")
                        //con.sendBroadcast(i)
                        LocalBroadcastManager.getInstance(con).sendBroadcast(i)
                    }else{
                        //  Toast.makeText(con, response.body().errorMessage, Toast.LENGTH_LONG).show()
                        val json = "{\"Status\": \"NOT OK\"," +
                                " \"ErrorMessage\": \"Something went wrong\" ," +
                                " \"Data\": \"NULL\", " +
                                " \"Timestamp\": \"NULL\" }"
    
                        searchData.value = gson.fromJson(json, AuthResponse::class.java)
                    }
                }
    
                override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
                    Log.e("API","Error")
                    val json = "{\"Status\": \"NOT OK\"," +
                             " \"ErrorMessage\": \"Something went wrong \"," +
                            " \"Data\": \"NULL\", " +
                            " \"Timestamp\": \"NULL\" }"
                    searchData.value = gson.fromJson(json, AuthResponse::class.java)
    
                }
            })
            searchData
        }
    
    }
    In above method getTopKeys following methods are showing in mainthread in profiler
    getJSON() - Related to gson
    setValue - setting value to livedata
    fromJSON - Related to gson
    j
    r
    2 replies · 3 participants
  • d

    Dominaezzz

    09/04/2022, 1:40 PM
    Does
    runTest
    not work with
    @BeforeTest
    ?
    e
    2 replies · 2 participants
  • o

    oday

    09/04/2022, 10:39 PM
    I dont know why I’m not able to run this coroutines code in standalone IntelliJ, I have a clue as to the Looper not being there means something is trying to access something Android specific, but not much clue otherwise.. is it because of the
    Main
    Dispatchers called there? there’s no Main thread like UI dispatcher in kotlin itself https://hastebin.com/eyolacixis.properties
    j
    15 replies · 2 participants
  • k

    Kieran Wallbanks

    09/05/2022, 4:31 PM
    So about
    runBlocking
    , I read that it shouldn't be used from a coroutine due to the potential for deadlocks (and we do seem to be encountering deadlocks here) but is there any way to "detect" if you're inside a coroutine somehow and run suspending methods in that coroutine instead of using
    runBlocking
    ? For reference, we're working inside a lot of pre-existing Java code that obviously can't be suspending, so I'm not sure how else to bridge it other than
    runBlocking
    , which obviously isn't great and doesn't seem to be working for us.
    m
    a
    +1
    24 replies · 4 participants
  • g

    George

    09/06/2022, 11:39 AM
    Pretty basic question, in cases like this:
    val account = async { getAccountByUuid(accountUUID) }
    val devices = async { deviceRepository.findDevicesByUuid(accountUUID) }
    account.await()?.addDevices(devices.await()) ?: return@coroutineScope null
    In case the account.await() is null, the devices.await() is still waiting or it is just canceled ? I believe it is canceled but just want to make it sure. Thanks in advance for any answers !
    s
    j
    4 replies · 3 participants
  • t

    Trey

    09/06/2022, 4:45 PM
    I'm converting some Java code that uses a BlockingQueue to use coroutines. I was starting to switch to using an actor, but I noticed that it is marked as being ObsoleteCoroutinesApi. What is the replacement? Also, why does the doc recommend this pattern if it is marked Obsolete? https://kotlinlang.org/docs/shared-mutable-state-and-concurrency.html#actors
    c
    f
    9 replies · 3 participants
  • k

    kenkyee

    09/06/2022, 5:29 PM
    Is there an interruptible callbackFlow (analogue to runInterruptible)? I.e., to timeout something that should get callbacks periodically that you’re trying to convert into a flow…
    e
    u
    12 replies · 3 participants
  • s

    Sam

    09/08/2022, 7:59 AM
    Something that came up yesterday when I was working with coroutines and thread locals: is there a way to use an inline higher-order function, but prevent its lambda parameter from suspending? Hypothetically something like:
    inline fun <T> foo(f: nosuspend () -> T): T
    e
    f
    +1
    9 replies · 4 participants
  • j

    Johnjake Talledo

    09/12/2022, 5:05 AM
    Hello guys I am having problem with my synchronous call, my use case is I wanted to finish all collection before launching
    doAnotherCall()
    , the
    viewModel.detailsState
    collects in a loop. I mean its
    emit and collect
    in a loop adding delay in
    doAnotherCall()
    does not help. Best Regards.
    private suspend fun collectProductList() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        viewLifecycleOwner.lifecycleScope.launch {
            viewModel.detailsState.collectLatest { state ->
                when (state) {
                    is ItemDetailState.ShowLoader -> binding.progressBar.visible()
                    is ItemDetailState.HideLoader -> binding.progressBar.gone()
                    is ItemDetailState.OnSuccess -> handleSubListSuccess(state.list, state.details)
                    is ItemDetailState.OnFailed -> handleFailure(state.error)
                }
            }
        }
        launch {
            doAnotherCall()
        }
    }
    j
    4 replies · 2 participants
  • p

    pakoito

    09/14/2022, 3:59 PM
    An easy one: I want a job queue, something that'd be like a PublishSubject in RxJava. I want an infinite stream that suspends if it goes over buffer and never drops values. I'm trying a MutableSharedFlow subscribed since object creation that acts on every new value:
    val pub = MutableSharedFlow<WorkJob>().apply { 
      onEach { println("Each") }
      .onStart { println("Start") }
      .onCompletion { println("Complete") }
      .launchIn(GlobalScope)
    }
    
    ...
    
    somewhere else in code:
    
    pub.tryEmit(WorkJob())
    That triggers "start" but doesn't emit any value. The moment I put
    MutableSharedFlow<Job>(replay = 10)
    it works, printing "start" and "each". But I want an infinite stream, not a repetition or something that goes to the latest value.
    c
    s
    8 replies · 3 participants
  • a

    Andrew Louis

    09/15/2022, 3:34 AM
    👋 Hey folks, I haven't had luck with any distributed tracing providers (or SDKs) that are functional with Kotlin coroutines / suspending functions. Some examples & description of common issues: • https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/6542 • https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/6502 • https://github.com/DataDog/dd-trace-java/issues/931 Surprisingly IBM's observability thing was the only one I found that seems to sell on working with coroutines - although was cost prohibitive for us. We could continue to use OpenTelemetry and setup the spans ourselves using a wrapper similar to this approach; but it winds up being pretty verbose and could be challenging to maintain. Would appreciate some insight / opinions on how to profile given the current state of the tracing tooling.
    p
    k
    2 replies · 3 participants
Powered by Linen
Title
a

Andrew Louis

09/15/2022, 3:34 AM
👋 Hey folks, I haven't had luck with any distributed tracing providers (or SDKs) that are functional with Kotlin coroutines / suspending functions. Some examples & description of common issues: • https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/6542 • https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/6502 • https://github.com/DataDog/dd-trace-java/issues/931 Surprisingly IBM's observability thing was the only one I found that seems to sell on working with coroutines - although was cost prohibitive for us. We could continue to use OpenTelemetry and setup the spans ourselves using a wrapper similar to this approach; but it winds up being pretty verbose and could be challenging to maintain. Would appreciate some insight / opinions on how to profile given the current state of the tracing tooling.
p

Pat Kujawa

09/17/2022, 12:19 AM
If you find something, I'm interested as well. We use new relic (and are migrating to the open telemetry agent for it) but still have to setup spans by hand.
k

Keith Miller

09/18/2022, 5:51 PM
same here
View count: 11