https://kotlinlang.org logo
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
  • x

    xenomachina

    03/05/2021, 11:45 PM
    Are there any plans for
    ReceiveChannel.isClosedForReceive
    to graduate from being "experimental"?
    • 1
    • 1
  • a

    Abhishek Dewan

    03/06/2021, 7:19 AM
    Hi I am not sure what I am doing wrong here. In my app I have an authenticationRepo that has two suspend methods. I am aware that using global scope is not the right way to start a coroutine but this is for testing purposes. The problem I am seeing is that after collecting the flow from the first call to authenticationRepo, I don’t see to be able to get the second call to authenticationRepo to fire (as can be seen from the recording). I am not sure if i am using flows incorrectly but I am unable to understand why is the second line of code not hitting
    adada.mov
    m
    l
    • 3
    • 4
  • r

    Rob

    03/06/2021, 6:44 PM
    Is there a way to block on a scope to finish it’s jobs while not causing a deadlock, if they’re on the same thread? I have cleanup code in the finally block that needs to run on the same thread before onStop completes.
    Untitled.kt
    e
    m
    • 3
    • 24
  • u

    ursus

    03/07/2021, 4:23 PM
    I have ViewModel, those are driven by Scope of
    Dispatcher.Main
    ViewModel has state, and therefore State (
    MutableStateFlow<State>
    ) should only be set on main thread -- to avoid synchronization Is there a way I can assert Scope is on main thread without an android reference? (
    Looper.myLooper() != Looper.getMainLooper()
    ) (To keep my viewmodels KMP ready) Or, should I just not care and read-write (reduce) to StateFlow within a synchronization block?
    a
    • 2
    • 24
  • m

    Marcin Wisniowski

    03/07/2021, 10:38 PM
    Is there a way to check a
    Channel
    size (without consuming the contents)? I'm currently counting
    send()
    and
    receive()
    calls manually.
    d
    • 2
    • 1
  • a

    Arun

    03/08/2021, 9:25 AM
    I want to cancel all old jobs in a CoroutineScope and start a new job in the same CoroutineScope. What’s the best way to do that?
    k
    t
    • 3
    • 3
  • t

    takahirom

    03/08/2021, 10:46 AM
    I have a question about the interpretation of the following sentences. Does this mean it's a good practice to use withContext{} in all functions, even if there is no blocking process in the Repository?
    A good practice is to use 
    withContext()
     to make sure every function is main-safe, which means that you can call the function from the main thread.
    https://developer.android.com/kotlin/coroutines/coroutines-adv#main-safety
    🇳🇴 1
    a
    u
    • 3
    • 2
  • a

    Andrew Ebling

    03/08/2021, 11:51 AM
    I have a stream of events coming into a
    ReceiveChanel
    every 10ms, representing the state of some buttons on an external controller. When I call a method, I need to wait until I see 10 no button press events, then 10 button press events of a given type in a row, followed by 10 no button press events, then call a supplied completion handler. So far I’ve got as far as this:
    fun readButtonPress(press: ButtonPress, completion: (ButtonPress) -> (Unit)) {
      launch {
         eventReceiveChannel
            .consumeAsFlow()
            // wait for:
            // at least 10x no press events
            // 10x or more press events
            // at least 10x no press events
            .consume {
                completion(buttonPress)
            }
         }
    }
    My questions are therefore: 1. am I on the right track? I want to contain coroutine use to this class, as it needs to be called from a callback-based API 2. what is the correct way to track state in this scenario (i.e. number of events received in a row of a given type)? 3. what are the correct flow methods to use to achieve this goal? I think I’ve just about got my head around coroutines conceptuals and beginning to get my head around Flow, but my brain is blowing a fuse trying to figure this out.
    a
    • 2
    • 2
  • t

    Timo Drick

    03/08/2021, 4:54 PM
    It looks like try catch around a background task will prevent interruption of a coroutine:
    val job1 = launch {
        try {
            withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                SystemClock.sleep(1000)
                throw IOException("Wurst")
            }
        } catch (err: Throwable) {
            Log.d("Test", "code executed")
        }
    }
    launch {
        delay(500)
        job1.cancel()
    }
    In this code the Log.d line will be executed. Which is bad when e.g.: i want to show a error message after a network call failed but the fragment coroutine scope is already cancelled. Is there any ellegant solution to avoid executing the catch when corotuine scope is already cancelled?
    t
    e
    c
    • 4
    • 61
  • a

    Andrew Ebling

    03/09/2021, 9:48 AM
    I would like to write some tests for an operator which filters button press events (see thread from yesterday). To get some inspiration for the right approach, I’ve been looking at some of the existing Kotlin Coroutine tests e.g.
    kotlinx.coroutines/kotlinx-coroutines-core/common/test/TestBase.common.kt
    . Is it possible to re-use
    TestBase()
    my own tests? I’ve tried
    import kotlin.test.*
    however this package is not found, despite having the following in my Android app `build.gradle`:
    implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3’
    I’ve also tried adding a
    testImplementation
    line with the same, but the above import still fails. Is re-using
    TestBase()
    etc. in my code not possible? Or is their a separate
    testImplementation
    entry I should add to my app
    build.gradle
    ?
    e
    • 2
    • 4
  • t

    Trần Đại Nhân (Max)

    03/10/2021, 3:10 AM
    Hi everyone, I have some confusion with two results, the first is Kotlin JVM and the second is Android Application. Anyone can help me to explain why it a difference in results with the same code logic?
    a
    p
    • 3
    • 9
  • a

    Andrew Ebling

    03/10/2021, 10:06 AM
    how do I cancel a flow after the first time
    collect { }
    completes? I’d like to do something like this, but the job val is not visible:
    val eventJob = launch {
       myChannel
          .consumeAsFlow()
          .filterAllButFinalEvent()
          .collect { event ->
              doSomething()
              eventJob.cancel() // doesn’t compile
          }
       }
    a
    • 2
    • 5
  • i

    Ivan Pavlov

    03/10/2021, 2:45 PM
    Hi. I have something like
    val sf1 = MutableStateFlow(listOf(1))
    val sf2 = MutableStateFlow(listOf(-1))
    
    sf1.value = listOf(1, 2)
    sf2.value = listOf(-1, -2)
    sf1.value = listOf(1, 2, 3)
    I combine them like
    sf1.combine(sf2) { a, b -> a + b }
        .stateIn(scope, SharingStarted.Eagerly, initialValue = listOf())
        .onEach { println(it) }
        .launchIn(scope)
    Then I don't have [1, -1] list in combined flow. I changed initialValue to sf1.value + sf2.value and now it works but I think that I could miss something which simplifies this. Is there a better way?
    m
    • 2
    • 1
  • x

    xenomachina

    03/10/2021, 6:22 PM
    I find that I frequently need a Job+SendChannel that sends to that job, where the Job acts as a consumer on the channel (internally it has the corresponding ReceiveChannel) and the job exits once the channel is closed for receive. I've built some small helper classes&functions to help with this, but I'm wondering if there's something already in kotlinx.coroutines I missed, or if there's some reason I shouldn't be doing things this way.
    a
    • 2
    • 6
  • z

    zak.taccardi

    03/10/2021, 8:59 PM
    How would you call a function if and only if a coroutine is suspended for more than X ms?
    log.verbose("awaiting for ${request.uri}")
    hasTokenStates
        .first { hasToken -> hasToken } // suspending
    log.verbose("awaiting complete for ${request.uri}")
    I want to only log
    "awaiting for ${request.uri}"
    if the
    first()
    suspends for more than `1_000`ms
    z
    • 2
    • 3
  • g

    Gilles Barbier

    03/11/2021, 10:20 AM
    Hi, Can some explain to me why:
    runBlocking {
            launch {
                println("a1")
                runBlocking { delay(100) }
                println("b1")
            }
    
            launch {
                println("a2")
                runBlocking { delay(300) }
                println("b2")
            }
        }
    displays a1 a2 b2 b1 - instead of a1 a2 b1 b2
    🤔 1
    l
    u
    +2
    • 5
    • 47
  • g

    Gilles Barbier

    03/11/2021, 10:21 AM
    (I my real code, the runBlocking are processed from a method.invoke to "wait", that why I can' t use suspend functions there) - How can I avoid this unexpected behvior?
    m
    u
    • 3
    • 13
  • j

    Javier

    03/11/2021, 11:33 AM
    The differences between
    1.4.3
    and
    1.4.3-native-mt
    are only in the native artifacts, in other words, jvm and android artifacts are the same?
    b
    • 2
    • 5
  • m

    Mateusz Krawczuk

    03/11/2021, 3:34 PM
    I’m trying to remove channel.consumeEach from bluetooth communication in my project. What is current best replacement for it? Should I use consumeAsFlow() and then just collect it?
    t
    • 2
    • 4
  • x

    xenomachina

    03/11/2021, 4:38 PM
    When I try to use the Coroutines tab in IntelliJ IDEA's debugger it says "An error occurred on fetching information". How do I get it working?
    l
    • 2
    • 6
  • m

    muliyul

    03/11/2021, 5:07 PM
    Assume I have this:
    runBlocking {
     ...
     collection.asFlow().flowOn(<http://Dispatchers.IO|Dispatchers.IO>).fold(0) { acc, next ->
      acc + calculate(next)
     }
    }
    Does it matter if the
    calculate
    function is suspending or not in terms of performance?
    a
    • 2
    • 1
  • x

    xenomachina

    03/11/2021, 5:18 PM
    How does one debug deadlocks in coroutines? What I'd like to be able to do is run the code until it deadlocks, and see a snapshot of where each coroutine is "stuck". The coroutines tab in the debugger doesn't work, so I've just been adding logging around every suspend point I think could be responsible. This "works", but is incredibly tedious and slow, and also error-prone because it'll fail if I don't think of the guilty suspend point when adding my logging. Is there a better way?
    l
    u
    • 3
    • 25
  • a

    Abhishek Dewan

    03/12/2021, 5:39 AM
    I am working on a KMM project where I have the following class
    @ExperimentalTime
    internal class AuthenticationRepositoryImpl(
        private val authenticationApi: AuthenticationApi,
        private val authenticationQueries: AuthenticationQueries
    ) : AuthenticationRepository {
    
        override suspend fun authenticateUser() {
            authenticationQueries.clearAuthenticationData()
            authenticationApi.authenticateUser().toAuthentication().apply {
                authenticationQueries.setAuthenticationData(accessToken, expiresBy)
            }
        }
    
        @ExperimentalTime
        override suspend fun getAuthenticationData(): Flow<Authentication?> {
            val timeNow = Clock.System.now().epochSeconds
            return authenticationQueries.getAuthenticationData(timeNow).asFlow().mapToOneOrNull()
        }
    }
    and I am calling the functions from my android app like so:
    fun checkAuthentication() {
        viewModelScope.launch {
            authenticationRepository.getAuthenticationData().onEach {
                if (it != null) {
                    Timber.d("Valid Authentication Found")
                    isAuthenticationValid.value = true
                } else {
                    Timber.d("Valid Authentication Not Found - Requesting Authentication")
                    authenticationRepository.authenticateUser()
                }
            }.collect()
        }
    }
    In the following code if the authentication data is not present in the SqlDelight DB, I get a null in the onEach of the flow and then I trigger a fetch and save to DB. However, the save to DB does not re-trigger a flow update. Is there something I am doing wrong here?
    • 1
    • 4
  • u

    uli

    03/12/2021, 10:43 AM
    I just learned a lot about run blocking from this thread: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1615458029368600 Just for reference: 1. two
    runBlocking
    , launched on the same single threaded dispatcher do not block each other. They share an event queue. 2. former
    runBlocking
    will only return after later
    runBLocking
    completes (1) comes as a positive surprise (2) is totaly unexpected and I’d consider it a bug I’ll follow up in a thread with the demo code
    ❎ 1
    👍 1
    m
    l
    • 3
    • 46
  • j

    Jason5lee

    03/12/2021, 12:33 PM
    What is the best practice to work with
    org.reactivestreams.Publisher
    in coroutine?
    c
    • 2
    • 2
  • j

    james

    03/12/2021, 1:43 PM
    Hello) I have some concern
    private fun loadData() = with(presenterScope) {
        listOf(
            async {
                 metadata = transferOtherBank.getMetadata()
            },
            async {
                sources = transferOtherBank.getSourceList()
            },
            async {
                favorites = transferOtherBank.getFavorites()
            },
            async {
                fee = transferOtherBank.getTransactionFee()
            },
            async {
                banks = transferOtherBank.getBanks()
            }
        )
    }
    where presenterScope is Coroutine scope provided by moxy2 library (I can attach implementation if it’s necessary)
    presenterScope.launch {
        loadData().awaitAll()
        setName(favorites, banks)
    
        Timber.d("ASSSAS after await")
    
    }
    Once some of async fails (getFavorites for example) setName(…) function is never called. How can I ensure calling of setName(…) despite any error in any async? Thanks!
    d
    l
    m
    • 4
    • 5
  • k

    kevin.cianfarini

    03/12/2021, 2:34 PM
    Is setting the value on a MutableStateFlow thread safe?
    :yes-black: 3
    a
    • 2
    • 4
  • n

    Nikola Milovic

    03/13/2021, 7:32 AM
    Is this an okay approach to download images from an URL while saving them to local storage. It should happen in parallel and I need to await for all three images to return their URI before proceeding. I kinda dislike the
    if (edgesUri.getCompleted() == null
    null checks and the
    labelUri.getCompleted()!!.path!!
    . Any way to improve this?
    suspend fun saveImageToDB(networkImageModel: CBImageNetworkModel): Result<Long> {
            return withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                try {       
                    val edgesUri = this.async {
                        val urlEdges = URL(networkImageModel.edgesImageUrl)
                        return@async saveBitmapToAppStorage(urlEdges.openStream(), ImageType.EDGES)
                    }
                    val finalUri = this.async {
                        val urlFinal = URL(networkImageModel.finalImageUrl) 
                        return@async saveBitmapToAppStorage(urlFinal.openStream(), ImageType.FINAL)
    
                    }
                    val labelUri = this.async {
                        val urlLabels = URL(networkImageModel.labelsImageUrl)
                        return@async saveBitmapToAppStorage(urlLabels.openStream(), ImageType.LABELS)
                    }
    
                    awaitAll(edgesUri, finalUri, labelUri)
    
                    if (edgesUri.getCompleted() == null || finalUri.getCompleted() == null || labelUri.getCompleted() == null) {
                         Result.failure<Long>(Exception("An image couldn't be saved"))
                    }
    
                    val image = CBImageDataModel(
                        labelsImageUri = labelUri.getCompleted()!!.path!!,
                        finalImageUri = finalUri.getCompleted()!!.path!!,
                        edgesImageUri = edgesUri.getCompleted()!!.path!!,
                    )
                    Result.success(db.imageDao().insertImage(image))
                } catch (e: Exception) {
                    Timber.e(e)
                    Result.failure(e)
                }
            }
    o
    d
    • 3
    • 5
  • l

    leandro

    03/13/2021, 10:53 AM
    when I wrap an object that holds resources and requires a callback through a
    suspendCancellableCoroutine
    , do I need to cleanup the resources inside the error callback?
    suspend fun isSessionValid(): Boolean = suspendCancellableCoroutine { continuation ->
        lateinit var auth: Auth
    
        val callback = object : AuthHandler {
            override fun onSuccess(session: AuthUserSession) {
                continuation.resume(session.isValid)
                auth.release()
            }
    
            override fun onFailure(e: Exception) {
                continuation.resumeWithException(e)
            }
        }
    
        auth = builder.setAuthHandler(callback).build()
        auth.getSession()
        continuation.invokeOnCancellation { auth.release() }
    }
    d
    m
    • 3
    • 16
  • m

    Marcin Wisniowski

    03/13/2021, 11:18 PM
    How do I receive all elements from a
    Channel
    , whether it's 0 or more, not suspending either way?
    a
    • 2
    • 1
Powered by Linen
Title
m

Marcin Wisniowski

03/13/2021, 11:18 PM
How do I receive all elements from a
Channel
, whether it's 0 or more, not suspending either way?
a

Adam Powell

03/14/2021, 12:16 AM
.poll()
will do the trick so long as the channel element type isn't nullable
:thank-you: 1
View count: 5