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

    Eric Ampire [MOD]

    10/30/2020, 12:56 PM
    With LiveData we could easily reach the same logic, so I would like to know the difference between
    LiveData
    and
    StateFlow
    .
    class DownloadingModel {
    
       private val _state = MutableStateFlow<DownloadStatus>(DownloadStatus.NOT_REQUESTED)
       val state: StateFlow<DownloadStatus> get() = _state
    
       suspend fun download() {
           _state.value = DownloadStatus.INITIALIZED
           initializeConnection()
           processAvailableContent {
                   partialData: ByteArray,
                   downloadedBytes: Long,
                   totalBytes: Long
               ->
               storePartialData(partialData)
               _state = DownloadProgress(downloadedBytes.toDouble() / totalBytes)
           }
           _state.value = DownloadStatus.SUCCESS
       }
    }
    🔥 1
    👍 1
    l
    a
    • 3
    • 7
  • s

    Shawn Witte

    10/30/2020, 11:37 PM
    I have a question about coroutine scopes (or is it contexts?). When I need to launch a new coroutine from a
    suspend
    function, I usually wrap the
    launch
    or
    async
    call with
    withContext
    (although, it looks like I should be using
    coroutineScope
    a little more often). This will tie the new coroutines into the structured concurrency of the calling coroutine, which is all fine and dandy. On the other hand, suppose I had something along the lines of
    shortLivedScope.launch { 
        // some stuff
        longLivedScope.launch { performSomeTasks() }
        // some stuff
    }
    What is the relationship between the coroutines I have now launched?
    a
    s
    • 3
    • 10
  • f

    florent

    10/31/2020, 11:27 AM
    Hi, I have function like this where
    Result.UiUpdate.MovieList
    is a sealed class. Do you know why I have to add as Result and the compiler want me to remove it?
    ☝️ 1
    t
    • 2
    • 1
  • n

    natario1

    10/31/2020, 1:02 PM
    Just getting started with coroutines here... Given a
    val flow = MutableStateFlow<Boolean>(false)
    , How to write a function that suspends until the flow value is true for the first time?
    suspend fun waitUntilTrue() { ... }
    b
    • 2
    • 2
  • r

    rkeazor

    11/01/2020, 1:32 PM
    Anyone know how to resolve the kotlin.Result classncast exception issue?
    g
    • 2
    • 15
  • g

    Grantas33

    11/01/2020, 4:08 PM
    Hi, is there a way to globally attach some code logic to coroutine lifecycle methods?
    l
    z
    • 3
    • 8
  • l

    Lalit Sagar

    11/02/2020, 8:14 AM
    I went through the documentation of
    suspendCancellableCoroutine
    . It mentions that this function throws a
    CancellationException
    if the coroutine is cancelled or completed while suspended. In which case the coroutine is completed while suspended?
    e
    • 2
    • 2
  • w

    william

    11/03/2020, 2:03 AM
    If I am seeing
    Uncaught Kotlin exception: kotlinx.coroutines.CoroutinesInternalError: Fatal exception in coroutines machinery for DispatchedContinuation[WorkerCoroutineDispatcherImpl@169bc08, Continuation @ $start$lambda-1COROUTINE$34]. Please read KDoc to 'handleFatalException' method and report this incident to maintainers
    
    ...
    
    Caused by: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen dev.williamreed.clique.mobile.WsSession.$start$lambda-1COROUTINE$34@3b34238
    is this actually a bug in the library - or is the fault the "caused by" section from something I did?
    • 1
    • 1
  • j

    jean

    11/03/2020, 7:48 AM
    The doc on 
    StateFlow
     contains this statement:
    So a slow collector skips fast updates, but always collects the most recently emitted value.
    What’s the actual threshold that makes it skip states? Do I need to add a
    delay
    call if I want to force some State to NOT be skipped?
    t
    • 2
    • 3
  • p

    Pablo

    11/03/2020, 2:46 PM
    If I have a multiple call with async await or launch if I don't want to fail if one fails I need to use supervisorScope or supervisorJob? What's the difference between them?
    z
    • 2
    • 4
  • d

    Davide Giuseppe Farella

    11/03/2020, 5:29 PM
    Hello everyone, I got this scenario
    fun login(): Flow<LoginState>
    
    sealed class LoginState {
        object Loading : LoginState()
        class ApproveRequestToken(val url: String) : LoginState()
        object Completed : LoginState()
    }
    When the
    LoginState.ApproveRequestToken
    is emitted, I have to wait for user interaction ( approve token via web ), then I want the
    Flow
    to continue, what would be your best approach?
    b
    • 2
    • 2
  • e

    Erik

    11/03/2020, 7:03 PM
    How can a
    SingleLiveEvent
    (Android pattern when using view models and live data) be modeled using flows? I think that the documentation of
    fun <T> ReceiveChannel<T>.receiveAsFlow(): Flow<T>
    (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/receive-as-flow.html) describes this specific use case:
    Represents the given receive channel as a hot flow and receives from the channel in fan-out fashion every time this flow is collected. One element will be emitted to one collector only.
    So, if I just create a
    private val _events = Channel<MyEvent>()
    in my
    ViewModel
    and expose it as
    val events = _events.receiveAsFlow()
    , would that behave like a single live event? I.e.: one collector only receives the event, all others don't? Or are there additional things to consider? I'm a bit confused about the existence of
    (Mutable)SharedFlow
    (and the now obsolete
    BroadcastChannel
    ), but I think this will always share emissions between all active collectors (subscribers) and that's precisely what single live event tries to prevent, am I right?
    a
    g
    c
    • 4
    • 13
  • e

    Erik

    11/03/2020, 7:34 PM
    How can you easily assert values emitted by a flow that doesn't complete? Using
    TestCoroutineScope
    /
    -Dispatcher
    with
    runBlockingTest
    , when you
    flow.launchIn(testScope)
    , then the job would leak unless you remember to cancel the job before the test block ends. How can you verify more easily that a flow emitted certain values? I can think of some solutions: 1. As a side effect, put collected values in some mutable collection. This makes assertion of values easy, but you still have to remember to cancel any collectors of the uncompleted flow. 2. Cancel the source of the flow, i.e. force it to complete, by the end of the test. This should usually also complete collectors. 3. Do not use the test coroutine scope to collect flows that do not complete. This has a downside that you test with multiple scopes, which may be conceptually challenging. Either way it's a bit of test boilerplate 👎 Any ideas?
    👍 1
    i
    f
    +2
    • 5
    • 12
  • o

    octylFractal

    11/04/2020, 2:53 AM
    is there a known bug for
    Inappropriate blocking method call
    always appearing, even if wrapped in
    <http://Dispatchers.IO|Dispatchers.IO>
    ?
    • 1
    • 2
  • c

    Circusmagnus

    11/04/2020, 8:12 AM
    Given function:
    fun constructFlow() = flow { for(x in channel) emit(x) }
    Is there any practical difference between
    val someFlow = constructFlow()
    and
    val someFlow get() = constructFlow()
    ? I do realize, that second version will call constructFlow on every access, while first one - only once. But since a flow is only a definition of what should happen after collection - isn`t it always the same?
    z
    e
    • 3
    • 3
  • o

    Orhan Tozan

    11/05/2020, 1:47 PM
    I am trying to construct the following Flow, but with no luck. I am trying to do something like below, but it obviously doesn't compile (it's pseudo code). As you can see, I am trying to map a
    chatConversationsFlow: Flow<List<ChatConversation>>
    to a
    lastMessagesFlow: Flow<List<String>>
    . When the last message of a conversation is sent by me, the result will be of the format
    "You: ${chatConversation.lastMessage}"
    . But when the last message of a conversation is sent by someone else than me, I first need to get
    userFlow: Flow<User>
    of the specific user, then the result will be of the format
    "${user.name}: ${chatConversation.lastMessage}"
    . What would be the best (preferably most idiomatic) approach to achieve this in Flow/Coroutines?
    private fun lastMessagesFlow(
        chatConversationsFlow: Flow<List<ChatConversation>>
    ): Flow<List<String>> = flow {
        emit(listOf("Loading"))
    
        emitAll(
            chatConversationsFlow.map { chatConversations ->
                chatConversations.map { chatConversation ->
                    if (chatConversation.lastMessageSentByUserId == -1) "You: ${chatConversation.lastMessage}"
                    else {
                        val userFlow: Flow<User> = userFlow(userId = chatConversation.lastMessageSentByUserId)
                        userFlow.map { user ->
                            "${user.name}: ${chatConversation.lastMessage}"
                        }
                    }
    
                }
            }
        )
    }
    • 1
    • 1
  • r

    rsetkus

    11/05/2020, 3:17 PM
    Hi. Cannot sync recent coroutines native library from jcenter or maven central
    > Could not find org.jetbrains.kotlinx:kotlinx-coroutines-core-native:1.4.1.
         Searched in the following locations:
           - <https://dl.google.com/dl/android/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core-native/1.4.1/kotlinx-coroutines-core-native-1.4.1.pom>
           - <https://jcenter.bintray.com/org/jetbrains/kotlinx/kotlinx-coroutines-core-native/1.4.1/kotlinx-coroutines-core-native-1.4.1.pom>
           - <https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core-native/1.4.1/kotlinx-coroutines-core-native-1.4.1.pom>
    Latest I can sync is
    1.3.8
    Used remote repositories:
    allprojects {
        repositories {
            google()
            jcenter()
            mavenCentral()
        }
    }
    b
    l
    t
    • 4
    • 12
  • r

    rkeazor

    11/06/2020, 6:50 AM
    Untitled
    l
    • 2
    • 1
  • t

    Tomasz Krakowiak

    11/06/2020, 7:03 AM
    Is it possible to schedule a task to be executed AFTER current task completes or suspends?
    g
    • 2
    • 1
  • p

    Pablo

    11/06/2020, 11:16 AM
    Is there any way to check that a couroutineScope is cancelled? on my Unit test I want to check that my coroutineScope is cancelled at some point. The thing is my CoroutineScope is not a mock so I can not use verify.
    e
    g
    • 3
    • 4
  • a

    andylamax

    11/07/2020, 12:34 AM
    With the state of compose as of now, should we expect another ui package for coroutines?, say
    kotlinx-coroutines-compose
    With dedicated dispatchers for
    composables
    launching suspending functions?
    i
    • 2
    • 2
  • w

    WukongRework.exe

    11/07/2020, 2:23 AM
    hey, i was just wondering, is there a way to tell two separate coroutines to wait a specific time before continuing without having to cancelling them and then relaunching once both coroutines are done
    e
    e
    • 3
    • 4
  • s

    Shalom Halbert

    11/07/2020, 8:30 AM
    Is somebody able to share an explanation for why the test below prints
    9a
    9b
    9c
    9d
    9e
    9f
    when it seemingly should be printing
    1a
    2a
    3a
    4a
    5a
    6a
    7a
    8a
    before that?
    @Test
        fun example1(): Unit = runBlocking {
            val flowA = flowOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
            val flowB = flowOf("a", "b", "c", "d", "e", "f").onEach { delay(1000) }
    
            flowA.combine(flowB) { a, b -> "$a$b" }.collect { println(it) }
        }
    s
    t
    • 3
    • 3
  • l

    Luke

    11/07/2020, 7:38 PM
    Is there a way to map a
    StateFlow<T>
    to a
    StateFlow<R>
    ? I have a
    MutableStateFlow<MyEnum>
    in a view model, but I want it private to expose publicly a
    StateFlow<String>
    j
    s
    +2
    • 5
    • 14
  • b

    Bruno Ortiz

    11/08/2020, 3:18 PM
    How do i create a "infinite" flow correctly? I'm trying to create a flow to "infinitely" consume from a messagem bus. For example:
    fun receive(interval: Duration) = flow {
        while (true) {
            delay(interval.toMillis())
            val messages = getMessages(interval)
            messages.forEach {
                println("Emitting $it")
                emit(it)
            }
        }
    }
    I can consume the flow "forever" like this:
    receive(Duration.ofSeconds(1))
        .collect {
            println(it)
        }
    Or limit the number of messages that i consume:
    val amount = 10
    receive(Duration.ofSeconds(1))
        .take(amount)
        .collect {
            println(it)
        }
    I tested this and the flow "completes", but i do not understand what happens in the second case, do the
    while(true)
    loop gets suspended forever? Is this a problem?
    a
    • 2
    • 3
  • b

    Brendan Weinstein

    11/08/2020, 5:16 PM
    Is there a
    native-mt
    variant of coroutines 1.4.1?
    🇳🇴 1
    ☝️ 3
    a
    • 2
    • 1
  • s

    Slackbot

    11/09/2020, 11:38 AM
    This message was deleted.
    g
    • 2
    • 1
  • g

    gsala

    11/09/2020, 12:00 PM
    Is it a bad idea to pass a
    CoroutineScope
    to a function, instead of making the function suspendable and then call
    coroutineScope {}
    inside? What I'm going for:
    fun connect(
                device: BluetoothDevice,
                connectionScope: CoroutineScope,
        ): StateFlow<BleConnectionState>
    I want to have the consumers of this API decide what the lifetime/scope of the BLE connection should be
    m
    w
    • 3
    • 3
  • y

    Yuri

    11/09/2020, 3:37 PM
    Hello everyone, tricky coroutine context question, will appreciate any help. I have 2 levels in my app:
    Core
    :
    CoroutineExceptionHandler {...} + SupervisorJob() + Dispatchers.Default
    UI
    :
    coreContext + (several custom elements holding activity reference) + Dispatchers.Main.immediate + SupervisorJob(coreContext[Job])
    Let’s say I have
    // core level
    class CoreModel(coreScope: CoroutineScope) {
      suspend fun operation(): Result {???}
    }
    
    // ui level
    uiContext.launch { 
      showResultInUi(coreModel.operation())
    }
    What is the correct way to implement
    operation()
    to run it on
    coreContext with job from current coroutine (to be cancelled when UI context is cancelled) and without custom elements (to prevent activity leaks)
    ? Ideally core level should know nothing about custom element’s keys.
    g
    • 2
    • 3
  • k

    kristianconk

    11/09/2020, 6:22 PM
    Hi everyone, I have a question, Is possible collect/process more than one flow inside launch block? my code is like
    launch{
    flow1.collect{ ... }
    flow2.collect{ ... }
    ...
    }
    but only flow1 is executed, if comment flow1 then flow2 is executed
    n
    j
    g
    • 4
    • 9
Powered by Linen
Title
k

kristianconk

11/09/2020, 6:22 PM
Hi everyone, I have a question, Is possible collect/process more than one flow inside launch block? my code is like
launch{
flow1.collect{ ... }
flow2.collect{ ... }
...
}
but only flow1 is executed, if comment flow1 then flow2 is executed
n

nrobi

11/09/2020, 6:25 PM
Well everything after the collect will suspend, until your first flow terminates/closes this way
So you need to collect them in different scopes
k

kristianconk

11/09/2020, 6:26 PM
wow, that make sense, my flow1 is an infinite loop
while(true){
emit(data)
delay(1000)
}
j

Jason Ostrander

11/09/2020, 6:37 PM
There is a convenience function for this: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/launch-in.html
👍 1
n

nrobi

11/09/2020, 6:39 PM
Yupp. Most of the time I'm also using the
flow.onEach { .... }.launchIn(yourScope)
as @Jason Ostrander suggested
k

kristianconk

11/09/2020, 6:40 PM
thank you! I will use it
g

gildor

11/09/2020, 11:33 PM
So you need to collect them in different scopes
Not different scopes, but different coroutine to collect each, scope can be the same
n

nrobi

11/10/2020, 4:09 AM
Yes, you're right. My bad, I didn't mean the
coroutineScope
, rather the scope of the lambda/launch
View count: 3