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

    Tomas Kormanak

    12/09/2021, 9:16 AM
    Hi, how do you debug coroutines? Right now I am getting cancelation exception
    Parent job is Cancelling
    but I can't figure out which coroutine failed and where.
    • 1
    • 1
  • t

    Thomas Flad

    12/09/2021, 12:42 PM
    Hi everyone 👋🏼 I want to use a SharedFlow created with the
    shareIn
    operator +
    WhileSubscribed
    to cancel/resume the SharedFlow in
    repeatOnLifecycle
    when the Android App goes to background. It’s working fine so far. I also combine this flow with a MutableStateFlow in my ViewModel to react on user input and update my state.
    class MyViewModel(
        dataSource: MyDataSource,
        sharingStarted: SharingStarted = WhileSubscribed(5000)
    ) : ViewModel() {
    
        var userInput = MutableStateFlow(1)
    
        val state = dataSource.dataFlow()
            .combine(userInput) { data, userInput ->
                OutputClass(data, userInput)
            }
            .shareIn(viewModelScope, sharingStarted, 1)
    
    }
    My issue is that I want to test this. I’ve tried to use Turbine for this but it does not help with the combine.
    @Test
    fun testMyViewModel() = runBlockingTest {
    
        val cut = MyViewModel(
            mockk { coEvery { dataFlow() } returns flowOf(Data()) },
            sharingStarted = SharingStarted.Eagerly
        )
    
        cut.state.test {
    
            // Also an emit to the userInput here does not help
            // cut.userInput.emit(2)
            
            assertEquals(OutputClass(...), awaitItem())
        }
    
    
    }
    I’m getting a timeout instead of the result.
    t
    u
    +2
    • 5
    • 10
  • a

    Andrew Kuryan

    12/10/2021, 12:01 AM
    Hey guys, do we currently have a way to write and read files asynchronously, or is this answer still valid?https://stackoverflow.com/a/50468907
    e
    • 2
    • 1
  • m

    Michael Clancy

    12/10/2021, 2:34 PM
    Hi there, trying to work out why a mutableStateFlow.value can be set from outside of a coroutine, I assume it was essentially a wrapper for emit(). Could anyone help me understand what im missing? Thanks, Michael
    y
    j
    • 3
    • 4
  • d

    dimsuz

    12/10/2021, 4:00 PM
    Naming question. Maybe offtopic? (naming is hard) I have a computation which reads a DB value, and some scenarios permit reading it in a suspending manner, but in others it's better to represent this value as stream, so API provides both ways
    suspend fun userList(): List<User>
    fun userList(): Flow<List<User>>
    Any idea on naming here, so that they don't conflict? in Rx we used to call the "blocking" one
    userListSync
    , and "sync" were rare beasts actually. But in coroutine world calling
    suspend
    function "sync" is not correct.
    j
    a
    +2
    • 5
    • 14
  • j

    Javier

    12/10/2021, 4:20 PM
    Using coroutines RC2 in a kmp library, I am seeing this error on my Windows machine.
    > Task :semver-core:linkDebugTestLinuxX64 FAILED
    e: Compilation failed: Cannot get target from triple x86_64-unknown-linux-gnu.
    d
    • 2
    • 8
  • m

    mcpiroman

    12/10/2021, 5:20 PM
    How can I use the same lock in both suspending and blocking code? `Mutex`seems to be only usable in suspend functions and `synchronized()`only in non-suspend.
    n
    • 2
    • 1
  • t

    Tolriq

    12/10/2021, 6:39 PM
    With RC2 flow.collect { value = it } no more works
    n
    m
    +2
    • 5
    • 6
  • j

    jeff

    12/10/2021, 8:46 PM
    is there some kind of compositeFlow or dynamic version of merge() or something? I need to expose a Flow that is (internally) comprised of multiple other flows, and be able to add to that internal list such that pre-existing collectors receive their items. I can envision how to write my own, I'm just wondering if there's a pre-existing solution
    u
    • 2
    • 3
  • c

    Clament John

    12/11/2021, 10:20 AM
    How do I do the following with LiveData
    private val searchString = MutableStateFlow("")
    val rooms = searchString.flatMapLatest {
            if (it.isBlank()) {
                fetchPrivateRooms()
            } else {
                fetchPrivateRooms().combineTransform(fetchPublicRooms()) { priv, pub ->
                    emit(filterRooms(priv, pub, it))
                }
            }
        }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
    Q: How do I do this if
    fetchPrivateRooms
    returns a
    LiveData<List<Rooms>>
    instead of a flow? I can't use observeAsState directly as I wish to merge and transform the data coming from the data source What is my usecase? I wish to use a library that uses livedata extensively in Compose. I've previously use the above code when I was working with
    flow
    But don't know how to merge and transform livedata within a viewmodel. Note: This business logic is to be seperated from the UI logic and so I can't use a lifecycleowner (I think)
    ✅ 1
    n
    • 2
    • 2
  • m

    mbonnin

    12/12/2021, 8:15 PM
    Not sure if it's a coroutines thing or a more global thing but Command-Clicking symbols like
    catch
    or
    retry
    in IntelliJ take me to a decompiled stub instead of the source. Is there anything I can do about this?
    e
    l
    • 3
    • 5
  • u

    ursus

    12/13/2021, 4:29 AM
    I'm new to Channels. I have a Downloader, which has a sequential BlockingQueue of download tasks. I need to enqueue, remove and view pending tasks. This is trivial with BlockingQueue. If I move this to a Channel, the sequential nature of it creates a queue, however how do I remove a enqueued or view all pending tasks? Do I need to keep track of the enqueues myself now?
    l
    v
    • 3
    • 3
  • j

    Joakim Forslund

    12/13/2021, 10:01 AM
    I have a flow that I use
    .collect {}
    on, however, I want to wait for a StateFlow/Boolean to be true before the collection can proceed, what is the recommended way of currently handling this? (None of the emits can be dropped, they need to wait for the StateFlow/Boolean to be true and emit as soon as it changes)
    s
    j
    u
    • 4
    • 17
  • t

    tylerwilson

    12/13/2021, 1:46 PM
    Is there a specific 1.6.0-RC2-native-mt, or is it built into 1.6.0-RC2 ?
    h
    • 2
    • 2
  • d

    dimsuz

    12/13/2021, 4:13 PM
    is there some quick way to forward collection to another flow? Something like
    val flowA: MutableSharedFlow<Int>
    
    flowB.collectTo(flowA)
    I know there's
    shareIn
    , but it creates a new flow, while I have an existing one.
    j
    z
    • 3
    • 6
  • g

    George

    12/13/2021, 8:11 PM
    Hi guys, I'm using spring boot webflux with kotlin and I was wondering if anyone knows the pros and cons of cast everything with asflow() since spring returns mono or flux. Implementations of mono and flux are based on coroutines since I use the coroutines reactive package .
    r
    t
    • 3
    • 5
  • s

    Simon Lin

    12/14/2021, 6:34 AM
    If I want the outputs and inputs have the same order but with different delays for each item. Is it efficient below?
    fun foo() {
        viewModelScope.launch {
            val inputList = listOf("a", "b", "c")
            val deferredList = mutableListOf<Deferred<String>>()
            repeat(3) { index ->
                deferredList += async {
                    delay((1L..10000L).random())
                    inputList[index]
                }
            }
            val outputList = deferredList.map { it.await() } // a, b, c
        }
    }
    t
    n
    • 3
    • 3
  • f

    Florian

    12/14/2021, 10:33 AM
    Is it possible that this gets stuck in
    runBlockingTest
    because
    TICK_DELAY
    is skipped so the CPU doesn't have time to execute something else? Normally, I leave this loop by collecting the value in another place and cancelling the coroutine around it.
    while (true) {
                        delay(TICK_DELAY)
                        val totalElapsedTime = systemClockProvider.getElapsedRealTime() - startTime
                        tasksDataSource.increaseMillisCompletedToday(
                            selectedTask.id,
                            totalElapsedTime - lastReportedTime
                        )
                        lastReportedTime = totalElapsedTime
                    }
    j
    e
    • 3
    • 4
  • u

    ursus

    12/14/2021, 12:54 PM
    How can I cancel a channel.send, that is waiting in receive buffer in unlimited?
    z
    • 2
    • 7
  • d

    dimsuz

    12/14/2021, 12:56 PM
    Flow docs mention that collection always happens in the "context of the calling coroutine". Does this mean that setting up flow and collecting it will happen on the same thread? I.e. is it safe to do read/write shared like this:
    suspend fun func() {
      var counter = 0
      someComplexFlow() // <-- potentially calls various withContext() inside its operators
        .collect { counter++ }
    }
    a
    • 2
    • 2
  • j

    Jonathan Olsson

    12/14/2021, 1:45 PM
    Hi! I thought
    suspend
    lambdas could be used just like normal lambdas. Why then is this not allowed?:
    fun main() {
        val f = suspend { i: Long ->
            delay(i)
        }
    
        runBlocking {
            f(1000L)
        }
    }
    h
    • 2
    • 2
  • h

    handstandsam

    12/14/2021, 2:28 PM
    Kotlin Actor support for Multiplatform is not planned. However, I would like to migrate some code to be multi-platform compatible. What is another way I could achieve the same behavior of an actor with multiplatform? Does anyone have some code to show how to do this? I’ve dug through old threads and google searches and shown the only replacement that was shared: https://gist.github.com/handstandsam/0ac44478f5378c079904458b0a013f83
    👀 1
    s
    • 2
    • 8
  • w

    William Reed

    12/14/2021, 2:57 PM
    i want to expose a
    StateFlow
    in my viewmodel that is backed by the
    Flow
    based jetpack DataStore. Any recommendations on how to do this without using
    runBlocking
    to get the initial value? i was thinking of calling a
    suspend fun
    to do this in my view model
    init
    , but then the
    StateFlow
    would not be available as soon as it is requested by the view
    a
    • 2
    • 6
  • r

    Robert Jaros

    12/14/2021, 6:31 PM
    I was using this simple code till
    1.6.0-RC
    , but in
    1.6.0-RC2
    it's not working anymore because the
    collect
    extension function was removed with https://github.com/Kotlin/kotlinx.coroutines/pull/3047 :
    val stateFlow = MutableStateFlow(State())
            val actionFlow = MutableSharedFlow<Action>()
            launch {
                actionFlow.collect {
                    stateFlow.value = stateReducer(stateFlow.value, it)
                }
            }
    What is the correct way to implement this?
    a
    h
    • 3
    • 5
  • c

    Colton Idle

    12/15/2021, 4:30 AM
    I encounter this pattern a lot
    viewModelScope.launch {
     val thing: String = someSuspendFunctionThatReturnsAValue()
     aMethodCallThatIsAFlow(thing).collect {
       if (it.status == "SUCCESS"){
        state.success = true
        //should I call job.stop() here?
       }
     }
    }
    My problem is that I want the flowable to stop collecting. Can I just save a ref to the call to launch and then call stop()? Or is starting a flowable in a coroutine scope frowned upon in general?
    a
    f
    n
    • 4
    • 37
  • p

    Pablo

    12/15/2021, 3:23 PM
    I have a question guys, I'm trying to test my Presenter which is :
    internal class MyPresenter @Inject constructor(...) {
     private val _uiState = MutableStateFlow<Foo>(Foo.Loading)
     override val uiState: StateFlow<Foo> = _uiState
     private val _sideEffect = MutableSharedFlow<Foo2>()
     override val sideEffect : SharedFlow<Foo2> = _sideEffect
    }
    
    init {
      scope.launch {
        usecase.getBar().fold(
         onSuccess = { _uiState.emit(mapper(whatever)) 
          if(...) _sideEffect.emit(whatever)
         }
         onFailure = { _uiState.emit(handleError(it)) }
      }
    }
    I'm trying to handle these emit, but I'm not succeeding I'm trying with the library app.cash.turbine but is throwing me an error...
    kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1000 ms
    (Coroutine boundary)
    What I'm doing in the test is :
    @Test
    fun test() {
      //given with the usecase call and willReturn what I want
      //given with the mapper call and willReturn what I want
      //Init presenter so the init {} method gets fired 
      presenter.uiState.test { 
       assertEquals(WhatIExpect, awaitItem())
       awaitComplete()
    }
    But it's not working, is there something I'm missing?
    n
    • 2
    • 3
  • n

    nilTheDev

    12/15/2021, 5:39 PM
    I am wondering whether
    stateFlow
    emit changes when done in a nested value. For context, consider this example,
    data class Person(var name: String)
    
    class SomeViewModel : ViewModel() {
        // made public for brevity
        val state = MutableStateFlow( listOf(Person("John")) )
    
        init {
            // will this change be emitted?
            state.value[0].name = "Bob"
        }
    
    }
    Will the change in the
    init
    block be emitted? I am pretty sure that
    liveData
    wouldn't emit this change. But would
    stateFlow
    do that?
    🇳🇴 3
    n
    • 2
    • 2
  • g

    groostav

    12/15/2021, 7:52 PM
    ok so, is there a way I can tell kotlinc to generate coroutine closures with all variables always? I don't want things to be optimised out. I want them under the debugger and im happy to pay the extra field costs to get it.
    e
    • 2
    • 1
  • s

    Sangmin Lee

    12/16/2021, 4:20 AM
    Hi. I’m wondering if it’s possible to happen that coroutine launch executed twich in spring @Transactional.
    • 1
    • 2
  • f

    frankelot

    12/16/2021, 6:29 PM
    👋 , I’d like to have a
    suspending fun
    that puts something in a queue and suspends until that “something” gets its turn and is finished being processed
    n
    c
    +2
    • 5
    • 15
Powered by Linen
Title
f

frankelot

12/16/2021, 6:29 PM
👋 , I’d like to have a
suspending fun
that puts something in a queue and suspends until that “something” gets its turn and is finished being processed
seems trivial.. but I’m having trouble getting it to work
the “processor” deals with shared mutable data so I want things to be processed sequentially one by one
Tried using channels and actors but
.send()
suspends until the channel has buffer capacity and starts processing… not when its done processing
n

Nick Allen

12/16/2021, 6:54 PM
Sounds like you just want a coroutine
Mutex
f

frankelot

12/16/2021, 6:57 PM
I think you are right, taking a look
somehow the idea of “mutex are no longer needed with coroutines” got into my head
c

Casey Brooks

12/16/2021, 6:57 PM
The purpose of channels is to make a "pipeline" of async communication. Putting an item into a channel and then waiting for processing to complete isn't how they're intended to be used, which is why it's not working for you. A better pattern would be to have something put an item into Channel A, and when that item is done have it put an item into Channel B to be processed later. And ultimately when the whole pipeline is finished, data is posted back to the original caller through a callback or something like that. This would loosely be considered an "actor pattern" Alternatively, a
Flow
might be a better mechanism than raw channels, since by design the emitter will suspend until the collector has finished processing the item
n

Nick Allen

12/16/2021, 6:57 PM
The queue thing is possible with a
CompleteableJob
in the item to signal when done but it’s easy to mess up error situations and you lose natural structured concurrency
f

frankelot

12/16/2021, 7:04 PM
I’ll explore both approaches
mutex
and
flows
and report back, thanks! for the help
The purpose of channels is to make a “pipeline” of async communication. Putting an item into a channel and then waiting for processing to complete isn’t how they’re intended to be used, which is why it’s not working for you.
this makes sense.. I don’t want async communication
I was just using an actor to “group” mutliple coroutines into one and avoid concurrent modifications to state (which should be done using a mutex)
d

darkmoon_uk

12/16/2021, 11:38 PM
One approach to this would be to use the
suspendCoroutine
function e.g. in pseudocode:
fun queuedProcess(someParam: Param) = suspendCoroutine { continuation -> 
    addToQueue(param, continuation)
    ensureQueueIsRunning()
}
...and elsewhere, the queue processing calls
queueItem.continuation(result
)
To add some description to that;
suspendCoroutine
suspends the execution at that point and gives you a
Continuation
object that you can invoke with a result when you want that point of execution to continue. You can then store this object as part of your queued operation, and invoke it when the queued process completes.
k

K Merle

12/17/2021, 5:35 AM
You could possibly have a simple for loop of suspend functions and run them sequentially by your need.
c

Casey Brooks

12/17/2021, 3:38 PM
The
suspendCoroutine
route works, but it might be easier and make the intent clearer to use a CompletableDeferred, which would effectively do the same thing
View count: 3