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

    CLOVIS

    08/15/2021, 9:29 AM
    What is the correct way to implement a cache? I'm thinking of something like:
    val cache = HashMap<Id, Deferred<Value>>()
    val lock = Semaphore(1)
    val cacheJob = SupervisorJob()
    val cacheScope = CoroutineScope(cacheJob)
    
    suspend fun get(id: Id) {
      val r = lock.withPermit {
        if (cache[id] == null) {
          val c = CompletableDeferred()
          cacheScope.launch {
            c.complete(getElementFromNetwork(id))
          }
          c
        } else cache[id]
      }
    
      r.await()
    }
    I think that's generally safe, but I'm not sure if it will correctly handle all cases (the ID is invalid, ...)
    d
    e
    r
    • 4
    • 21
  • d

    Didier Villevalois

    08/17/2021, 12:33 PM
    Hi everyone! I'm trying to design a Kotlin API for ZeroMQ. My API currently resembles a lot to the `SendChannel`/`ReceiveChannel` API. I would like to implement some
    onReceive: SelectClause1<Message>
    and
    onSend: SelectClause2<Message, SendSocket>
    similar to the ones of the
    Channel
    API. Searching in this channel, I found: 1. some helpers to build select clauses https://gist.github.com/zach-klippenstein/fa4366388295282fa409c5085abada23 by @Zach Klippenstein (he/him) [MOD], however it seems to me that there are made to work with event callbacks, 2. a suggestion by @Matej Drobnič to use something like
    async { mySuspendFunction() }.onAwait
    , however I can't seem to build a proper
    SelectClause1
    with this. As ZeroMQ uses a polling mechanism, I don't quite figure out how to use either of these solutions. Also, the
    AbstractChannel
    code is quite overwhelming. Is there a paper/article discussing the possible
    SelectClause
    implementations somewhere? Do anyone of you have some hints or advices to give me? Thanks in advance!
    n
    • 2
    • 1
  • h

    Huan

    08/17/2021, 1:36 PM
    Hi, I am using a callbackFlow{} and I am not sure if I should use `offer`(deprecated) or
    trySend
    (experimental API). Could someone tell me what is the best choice?
    d
    • 2
    • 2
  • u

    ursus

    08/18/2021, 11:55 AM
    In crashlytics I'm seeing bunch of caught exceptions like this
    Non-fatal Exception: kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled
    
    Non-fatal Exception: kotlinx.coroutines.JobCancellationException: Job was cancelled
    and no stacktrace; are there supposed to be ignored?
    l
    m
    • 3
    • 9
  • a

    aidanvii

    08/19/2021, 1:59 PM
    I recently started using
    Result
    as a return type as of Kotlin 1.5. I’m having seemingly random crashes with suspending functions that return
    Result
    (I haven’t checked with other inline/value classes). it’s happening in the generated
    invokeSuspend
    :
    Fatal Exception: java.lang.ClassCastException
    java.util.ArrayList cannot be cast to kotlin.Result
    I don’t have reliable repro steps for it, it seems to happen on some android devices, at different places but all the same crash, but not always 😢 I’m really stumped with it. I’ve been looking at the difference in the decompiled bytecode between suspending and non suspending functions that return
    Result
    , I can see casting of some
    Object
    to
    Result
    , assuming that’s what’s failing 😕
    s
    e
    r
    • 4
    • 18
  • l

    liminal

    08/19/2021, 10:07 PM
    I have a concurrent execution of some tasks using async and awaitAll. How do I wrap the awaitAll in such a way that I can handle each task failure separately. Currently only the first failure is caught. I am using supervisor scope
    l
    j
    e
    • 4
    • 5
  • f

    Florian

    08/20/2021, 5:21 PM
    I read that coroutine delays are not precise. What will cause a
    delay
    to take longer than the specified time? And do you think this will work to get the actual passed time after a delay (for example for a countdown timer)?
    val timeBefore = SystemClock.elapsedRealtime()
    delay(TICK_DELAY)
    val timeAfter = SystemClock.elapsedRealtime()
    val passedTime = timeAfter - timeBefore
    l
    • 2
    • 4
  • j

    Johnjake Talledo

    08/21/2021, 9:39 AM
    Hello guys do you have any example of coroutine 
    SharedFlows
     
    shareIn
     in github or gitlab, I couldn't find good resources or articles with a sample. What I am trying to achieve is combine(flow1, flow2) with 
    shareIn
    , so I only need to
    getfetch
    once and share this to at least 3 fragments. I really appreciate if someone could help. Best Regards to all.
    a
    u
    • 3
    • 19
  • d

    Didier Villevalois

    08/22/2021, 12:27 PM
    Is there any reason that there is no
    SendChannel<E>.sendCatching(e: E): ChannelResult<Unit>
    like there is a
    ReceiveChannel<E>.receiveCatching(): ChannelResult<E>
    ?
    l
    • 2
    • 3
  • s

    Stylianos Gakis

    08/22/2021, 4:06 PM
    I was wondering, is it safe/good idea to use
    coroutineScope
    inside a flow operator? I have a flow I’m mapping on, and I want, depending on the value do some multiple suspending calls that I would optimally prefer to be done in parallel. Specific example inside the thread 🧵
    d
    n
    • 3
    • 8
  • m

    Marty Pitt

    08/23/2021, 8:14 AM
    Hi. I'd like a review / feedback of an approach I'm using, joining two libraries outside of our control - one that uses CompletableFuture<>, and one that uses
    suspend fun
    n
    • 2
    • 7
  • m

    magnumrocha

    08/23/2021, 2:50 PM
    hey guys, is it possible to test Flows on Kotlin Multiplatform (
    commonTest
    ,
    androidTest
    ,
    iosTest
    ) ? how to deal with Coroutine Context?
    a
    m
    • 3
    • 5
  • p

    Patrick Ramsey

    08/23/2021, 11:10 PM
    Question: is looking up the dispatcher a job is running on as simple as doing myJob[CoroutineDispatcher]? More generally, what’s the best way to check from a unit test which dispatcher a given job was run on, short of mocking <scope>.launch? Or is that in fact the best way
    a
    j
    • 3
    • 52
  • c

    CLOVIS

    08/24/2021, 10:17 AM
    When it comes to structured concurrency, it's often said that a class that encapsulates asynchronous operations (for example, a cache, an http client) should take a constructor parameter to explicitly setup structure. Should that parameter be a
    Job
    or a
    CoroutineScope
    ? So far I've been adding
    Job
    parameters, but then I have to declare another
    CoroutineScope
    field per class.
    z
    a
    d
    • 4
    • 7
  • k

    K Merle

    08/24/2021, 10:57 AM
    Should I make a suspend network call in a
    viewModelScope
    or inside compose function with side-effect with compose?
    z
    j
    a
    • 4
    • 4
  • s

    stojan

    08/24/2021, 1:20 PM
    Can we do something like this, but with
    CoroutineScope
    instead of a
    Job
    ? I need to launch a few suspend functions, and cancel them if a) the parent scope is canceled b) the VH scope is canceled (whatever comes first)
    l
    j
    a
    • 4
    • 6
  • f

    Florian

    08/24/2021, 6:37 PM
    Does the nested
    launch
    block around
    taskDao.increaseMillisCompletedToday
    (which is a database operation) look dangerous? I use this to measure time but without the nested
    launch
    , I think the length of the database operation itself is causing imprecision. The tick interval is every 1s.
    fun startTimer() {
        timerJob?.cancel()
        timerJob = applicationScope.launch {
            val selectedTask = selectedTask.first()
            if (selectedTask != null) {
                taskDao.updateLastActiveTimestamp(selectedTask.id, System.currentTimeMillis())
                startTimerService()
                timerRunningFlow.value = true
                while (true) {
                    val timeBefore = SystemClock.elapsedRealtime()
                    delay(TICK_DELAY)
                    val timeAfter = SystemClock.elapsedRealtime()
                    val elapsedTime = timeAfter - timeBefore
                    launch {
                        taskDao.increaseMillisCompletedToday(selectedTask.id, elapsedTime)
                    }
                }
            }
        }
    }
    g
    n
    • 3
    • 7
  • p

    Patrick Ramsey

    08/25/2021, 1:58 AM
    Question --- Channel.consumeEach() (a suspend function) seems to be implemented internally as
    for (e in this) action(e)
    — which looks like it’s implicitly calling this.iterator() and iterating over the channel that way. I assume that can’t actually be what’s happening (right?) since Iterator.next() is blocking. Or does Channel.consumeEach() actually block?
    c
    • 2
    • 3
  • m

    Mickey Donaghy

    08/25/2021, 8:49 AM
    hi, if I cancel a coroutine 
    Job
     is there a way to find out where it was stuck? I can pass a 
    CancellationException
     in, but what I really want is a traceback for where it was when it got cancelled.
    e
    • 2
    • 4
  • e

    Erik Dreyer

    08/25/2021, 3:04 PM
    This might be more of a Spring Webflux question, but here goes… Say I have this controller method
    @PostMapping(path = ["/foo"])
      suspend fun example(): Flow<String> {
        val flux: Flux<String> = service.returnsFlux()
        return flux // <-- how to convert to Flow?
      }
    (this is a trivial example, but I have an API that returns a
    FLux<T>
    ) I’m trying to figure out how to go from a
    Mono/Flux
    back to the kotlin coroutines approach for Spring Webflux. I’d appreciate any help .
    i
    • 2
    • 3
  • e

    Eric Ampire [MOD]

    08/25/2021, 3:05 PM
    Hello I'm wandering what can the advantage of having such kind of structure ?
    l
    • 2
    • 8
  • c

    Chris Fillmore

    08/25/2021, 5:27 PM
    Hello, I’m trying to understand best practice for creating a CoroutineScope for some component I have. I don’t know what the difference is between these two approaches: CoroutineScope from Dispatcher:
    class MyComponent {
      private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
      
      fun close() {
        scope.cancel()
      }
    }
    CoroutineScope with Dispatcher + Job:
    class MyComponent {
      private val job = Job()
      private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + job)
    
      fun close() {
        job.cancel()
      }
    }
    The second example is used e.g. in https://kenkyee.medium.com/android-kotlin-coroutine-best-practices-bc033fed62e7 I’m grateful for any insight! Thank you!
    ☝️ 3
    n
    • 2
    • 2
  • p

    Patrick Ramsey

    08/25/2021, 9:33 PM
    what are the rules for how coroutineContext is looked up? I’m finding it a little bit surprising to say the least. I’ve got a test (using mockk.io) structured roughly like this:
    @Test fun `some particular invariant holds true`() = runBlockingTest {
        coEvery { someSuspendingFunction() } coAnswers { 
            val dispatcher = coroutineContext[CoroutineDispatcher]
            ....
        }
        ....
    }
    No matter which CoroutineDispatcher someSuspendingFunction() was called on,
    dispatcher
    in this code seems to end up being the test dispatcher created by runBlockingTest. If, however, I structure it like this:
    private suspend fun mockImplementation() {
        val dispatcher = coroutineContext[CoroutineDispatcher]
    }
    
    @Test fun `some particular invariant holds true`() = runBlockingTest {
        coEvery { someSuspendingFunction() } coAnswers {
            mockImplementation()
        }
    }
    dispatcher
    (in mockImplementation()) matches the dispatcher that someSuspendingFunction() was called on. IE… it looks an awful like the coAnswers block is running on that dispatcher, but
    coroutineContext
    specifically inside that block is reporting something different. Put differently --- coroutineContext seems to be returning the context from the enclosing lexical scope, rather than the context of the actual running coroutine. Is that expected?
    • 1
    • 6
  • s

    Scott Kruse

    08/25/2021, 11:44 PM
    What is BroadcastChannel getting replaced by?
    g
    • 2
    • 2
  • p

    Patrick Ramsey

    08/26/2021, 1:02 AM
    I’m sorry to keep spamming this channel. I’ll try and keep it down after this. But: I’m having real trouble wrapping my head around the semantics of test dispatchers, specifically around how to test code that involves multiple dispatchers. From a test, I’m trying to call <some channel>.send(<some object>). This yields, which seems to cause dispatcher.advanceUntilIdle() to return (since the consumer is running on another dispatcher), which causes the test dispatcher to try to clean up and exit (even though the test isn’t finished), which causes it to throw IllegalStateException (as if the test had ended). I assume this is it functioning as it’s supposed to, but it leaves me at a little bit of a loss as to how to test this functionality.
    • 1
    • 5
  • a

    andylamax

    08/26/2021, 2:59 AM
    Uncharted Teritory. While attempting to run my generated javascript code on react native, I am getting
    process.nextTick is not a function. (In 'process.nextTick(this._get_messageQueue__1()._processQueue)', 'process.nextTick' is undefined)
    at node_modules/@picortex/pi-monitor-client-sdk/pi-monitor-client-sdk.js:13160:17 in <anonymous>
    Checking that line number, I see the following generated code
    NodeDispatcher.prototype.scheduleQueueProcessing_1 = function () {
        process.nextTick(this._get_messageQueue__1()._processQueue);
      };
    I think for some reasons, the library thinks it is running in a node environment. Is there a way I can make this work differently? Any work around?
    j
    • 2
    • 3
  • s

    Scott Kruse

    08/26/2021, 3:36 AM
    I was getting
    Unresolved reference: last
    when referencing `
    import kotlinx.coroutines.flow.last
    from a unit test. Any ideas?
    • 1
    • 3
  • a

    Ananiya

    08/26/2021, 9:15 AM
    Hello there, I am bit confused I was trying to excute the Result once the main job completes but it never emit inside
    invokeOnCompletion
    even after I surround it within coroutine
    liveData {
        val mainJob = viewModelScope.launch {
               emit(Result.LOADING)
               repo.add(data)
              
        }
        mainJob.join()
        mainJob.invokeOnCompletion {
            viewModelScope.launch {
            if(it != null) emit(Result.FAILED(it) else emit(Result.SUCCESS(null)
            } 
         }
    }
    Alternatively if I do
    liveData {
       val mainJob = viewModelScope.launch {
                emit(Result.LOADING)
                repo.add(data)
                emit(Result.SUCCESS(null)
               
         }
         mainJob.join()
    }
    But I need to handle if it complete with in failure or success
    n
    • 2
    • 3
  • s

    spierce7

    08/26/2021, 5:00 PM
    Whats the best practice when you have a try catch block that catches
    Throwable
    inside a coroutine with CancellationException? I’m not relying on
    CancellationException
    anywhere in code, and I don’t want it to show up in my logs. Should I just be watching for it and then re-throwing it, or is it acceptable to just eat it and not throw it?
    } catch (e: CancellationException) {
                    throw e
                } catch (t: Throwable) {
                    logger.w(RuntimeException("Error validating file", t))
                    count++
                }
    l
    • 2
    • 3
  • v

    Vikas Singh

    08/26/2021, 5:32 PM
    Does coroutine require dependency I have not added any dependency still I am able to access the coroutinescope ?
    n
    • 2
    • 6
Powered by Linen
Title
v

Vikas Singh

08/26/2021, 5:32 PM
Does coroutine require dependency I have not added any dependency still I am able to access the coroutinescope ?
n

Nick Allen

08/26/2021, 5:44 PM
Yes. If you depend on a library that depends on the coroutine library, then you have the dependency transitively. I'd recommend an explicit dependency just so you can better control the version brought in.
Here's the main one:
dependencies {
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1'
}
There's others for interop with CompleteableFuture, RxJava, Android, and more.
v

Vikas Singh

08/26/2021, 5:51 PM
I have not added any other dependency and all dependencies are using implementation configuration so transitive is not possible
These are the dependencies in the gradle
n

Nick Allen

08/26/2021, 5:59 PM
Try
gradlew :app:dependencies
to see the full dependency tree. (assuming your module is
:app
)
👍 1
v

Vikas Singh

08/26/2021, 6:34 PM
Thanks found it it's with compose ui test
View count: 2