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

    Circusmagnus

    12/23/2020, 12:35 PM
    Is it possible to check whether sending to Channel will suspend without actually sending anything? I know, that there is
    isFull()
    function on SendChannel, but that is depracated without replacement
    b
    • 2
    • 2
  • j

    jean

    12/23/2020, 1:09 PM
    I’m having trouble to really understand how one should test coroutines/flow. I have this dummy code :
    @get:Rule
    val coroutineTestRule = CoroutineTestRule()
    
    class StateFlowTestClass(
        coroutineDispatcher: CoroutineDispatcher = Dispatchers.Main
    ) {
        private val _state = MutableStateFlow(0)
        val state: StateFlow<Int> = _state
    
        init {
            CoroutineScope(coroutineDispatcher).launch {
                blockingTask()
            }
        }
    
        private suspend fun blockingTask() {
            delay(10.seconds)
            _state.value = 1
        }
    }
    
    @Test
    fun `test on StateFlow`() = coroutineTestRule.runBlockingTest {
        advanceTimeBy(11.seconds.toLongMilliseconds())
        val value = StateFlowTestClass(TestCoroutineDispatcher()).state.value
        Assert.assertEquals(1, value)
    }
    when I run test on StateFlow I get the following error :
    java.lang.AssertionError: Expected:1, Actual:0
    . How am I suppose to fix this? How about when there is no delay but just a bunch of code taking time to execute, is there a way to wait it to be done?
    t
    • 2
    • 4
  • n

    Nikky

    12/23/2020, 10:28 PM
    so i know i cannot block on javascript.. but does anyone have a snippet for kotlin-js that does approximately the same thing as runBlocking and returning the result ? something like
    val derferred = async {  ... }
    while(!deferred.isCompleted) {
       delay(10)
    }
    return deferred.getCompleted()
    except since i am not in a coroutine i cannot use delay outside of it..
    m
    b
    • 3
    • 5
  • c

    Christopher Elías

    12/25/2020, 11:37 PM
    Hello, have anyone tried to implement something like RxJava PublishSubject with Coroutines? If so, could you please show some examples or gists?
    k
    b
    u
    • 4
    • 9
  • r

    Robert Jaros

    12/26/2020, 12:23 AM
    Hello. Let's say I want to process data from the
    ReceiveChannel
    and then pass the channel somewhere else in my app. Is the following approach a good solution (in sense of resources consumption and performance)? 1. Transform the channel to a
    Flow
    with
    consumeAsFlow()
    2. Use a bunch for different flow operations (
    map
    ,
    mapNotNull
    etc.) 3. Transform
    Flow
    back to the
    ReceiveChannel
    with
    produceIn()
    d
    • 2
    • 1
  • a

    Andrew Gazelka

    12/28/2020, 12:39 AM
    Is there a
    shareIn
    alt which evaluates lazily? i.e.,
    aFlow = flow(1,2,3).onEach{ println("A $it") }
    shared = aFlow.lazyCache()
    shared.take(1).forEach{ println("B $it")}
    shared.take(2).forEach{ println("C $it")}
    would print “A1 B1 A2 C2" … or something to that effect
    t
    t
    • 3
    • 4
  • a

    Andrew Gazelka

    12/28/2020, 1:15 AM
    came up with something that accomplishes my goals well enough
    r
    l
    d
    • 4
    • 4
  • c

    christophsturm

    12/30/2020, 4:27 PM
    if I use launch {} with a multithreaded coroutines dispatcher, will the whole launch block run in the same thread, or will the thread change possibly after return from a suspend method?
    a
    a
    z
    • 4
    • 5
  • a

    andylamax

    12/31/2020, 1:30 PM
    Are coroutines in kotlin js backed by javascript generators at any point? Just curious
    g
    • 2
    • 2
  • m

    Marc Knaup

    01/01/2021, 4:10 PM
    I still struggle with fully understanding scopes & contexts. Let’s say I have two scopes and would like to perform some suspendable work that is canceled if either of the two scopes is canceled. Is this sufficient?
    withContext(scope1.coroutineContext) {
        withContext(scope2.coroutineContext) {
            doSomeWork()
        }
    }
    Similarly with `Job`:
    val context2 = scope1.coroutineContext + SupervisorJob()
    
    withContext(scope1.coroutineContext) {
         withContext(context2) {
             doSomeWork()
         }
    }
    Would the cancellation of one context affect the other context? Is that the proper way to do that?
    d
    • 2
    • 2
  • p

    Peter Ertl

    01/02/2021, 11:16 PM
    do kotlin flows provide a mean of batching items into collections? e.g.
    flow.batch(size=20).collect { items -> /* do some batched operation e.g. a database insert */ }
    b
    • 2
    • 1
  • b

    Brais Gabin

    01/03/2021, 11:19 AM
    👋 I want to convert the
    Stream
    returned by
    Files.walk(Path)
    to a
    Flow
    . I could use the extension function
    consumeAsFlow()
    but
    Files.walk(Path)
    blocks the calling thread. So, what's the correct way to do it? I implemented this but it doesn't feel right:
    flow<Path> {
        Files.walk(path)
            .forEach { path -> runBlocking { emit(path) } }
    }
    .flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
    And, as side question, is there any library that implements the filesystem api as correct suspend functions?
    k
    t
    d
    • 4
    • 9
  • j

    João Eudes Lima

    01/04/2021, 2:14 AM
    g
    b
    • 3
    • 15
  • t

    Tim Malseed

    01/04/2021, 6:23 AM
    I have an
    Actor
    , and I'd like to be able to remove/cancel an operation when a new one comes in, depending on the progress of the previous operation.
    t
    • 2
    • 5
  • r

    Rainer Schlonvoigt

    01/04/2021, 11:06 AM
    really stupid question, but i can’t find an answer by googling… Are there any guarantees on order of execution when using a single threaded coroutine dispatcher? e.g.:
    val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
    val scope = CoroutineScope(dispatcher)
    
    for (i in 1..5) {
        scope.launch {
            println(i)
        }
    }
    t
    a
    +2
    • 5
    • 8
  • r

    rtsketo

    01/04/2021, 1:05 PM
    How come
    Main.immediate
    isn't the default dispatcher of
    MainScope()
    ? Is there any disadvantage in using
    immediate
    ?
    g
    • 2
    • 1
  • m

    Mark

    01/04/2021, 1:17 PM
    I have this function
    suspend fun foo(progressLambda: (Long) -> Unit)
    and I want to convert this to a function returning a
    StateFlow<State>
    where
    State
    is a sealed class providing
    Progress
    ,
    Success
    etc. Initially I thought of using
    callbackFlow
    but that seems to be more for functions that run asynchronously. Is there a more appropriate way?
    g
    • 2
    • 24
  • k

    Kshitij Patil

    01/05/2021, 11:53 AM
    I'm emitting a state and I want it to be cleared after receiving by an observer, I'm currently using
    StateFlow
    and after changing the state to desired object, I immediately set it back to null. This already sounding a bad practice so could someone guide me here with which Coroutine Flow/Channel should I use?
    d
    • 2
    • 1
  • y

    Yevhenii Datsenko

    01/05/2021, 12:35 PM
    Hello everyone and Happy New Year 🎉 I have a question about SharedFlow. According to documentation
    A default implementation of a shared flow that is created with MutableSharedFlow() constructor function without parameters has no replay cache nor additional buffer. emit call to such a shared flow suspends until all subscribers receive the emitted value and returns immediately if there are no subscribers. Thus, tryEmit call succeeds and returns true only if there are no subscribers (in which case the emitted value is immediately lost).
    That means that we might lose some emitted values. To tackle this problem I created the following function:
    /**
     * This function emits value when the receiver shared flow gets the first subscriber
     * It helps to avoid loosing events while view is not subscribed to shared flow
     */
    suspend fun <T> MutableSharedFlow<T>.emitLazily(value: T) {
        subscriptionCount.first { it > 0 }
        emit(value)
    }
    The question is will the 
    first
     function throw an 
    NoSuchElementException
     in this case? As far as I understand, it should not do it 😄) Because, the shared flow never completes and we can not convert it into a completing one without adding subscriber. It will be extremely helpful to hear your thoughts))
    n
    t
    • 3
    • 7
  • c

    Colton Idle

    01/05/2021, 1:36 PM
    I want to perform an event every 10 minutes so I'm following this code. https://stackoverflow.com/questions/54827455/how-to-implement-timer-with-kotlin-coroutines
    val tickerChannel = ticker(delayMillis = 10 * 60_000, initialDelayMillis = 0)
    
    repeat(10) {
        tickerChannel.receive()
        println("TIMER SUCCESS")
    }
    I want it to repeat forever though. I'm probably missing something dumb, but can I signify forever somehow, or do I have to use Integer.MAX_VALUE?
    w
    • 2
    • 3
  • m

    myanmarking

    01/05/2021, 1:45 PM
    If i assign the listener to a file level variable outside the method, and clear it inside awaitClose, it does work
    s
    t
    l
    • 4
    • 18
  • r

    Rob

    01/06/2021, 12:34 AM
    Are there non-blocking suspend functions in the standard library that replace these blocking ones FileInputStream.read() FileOutputStream.write()?
    👀 1
    z
    g
    +2
    • 5
    • 37
  • j

    jeff

    01/06/2021, 4:52 PM
    I understand that flows are sequential. So even if there's a delay it doesn't disrupt the ordering. But what if I want to disrupt the ordering? Details in :thread-please:
    d
    • 2
    • 5
  • u

    ursus

    01/07/2021, 1:30 AM
    I want to ask about thread safety of state flow imperative reading/writing
    private val state = MutableStateFlow(IDLE)
    
    fun doSomething() {
        if (state.value == LOADING) return
        state.value = LOADING
        scope.launch {
            try {
                actuallyDoSomething()
                state.value = SUCCESS
            } catch(ex: Exception) {
                state.value = ERROR
            }
        }
    }
    i.e. this is not guaranteed to be only single execution, right? I need to make reading & writing of LOADING synchronized, correct?
    g
    • 2
    • 13
  • r

    Rob

    01/07/2021, 2:36 PM
    Is there an operator to combine the latest values from a
    List<Flow<T>>
    ? Something that would have this signature
    (List<Flow<T>>) -> Flow<List<T>>
    ? I’m updating a RecyclerView using
    AsyncListDiffer.submitIList()
    .
    t
    m
    d
    • 4
    • 13
  • l

    leandro

    01/07/2021, 3:29 PM
    If one was to model an unidirectional data-flow, which primitive would you use to represent the events that the UI can create back to the Presenter/ViewModel? I’m currently using a
    SendChannel
    backed by a
    RENDEZVOUS
    implementation, but wondering if
    MutableSharedFlow
    (with
    replay=0
    ) would be better (i assume due to less overhead?!)
    r
    a
    • 3
    • 21
  • t

    tylerwilson

    01/07/2021, 5:15 PM
    I wonder if anybody has played with integrating Flow in iOS Combine - perhaps something like flow.observeAsPublisher() or similar shortcut…
    j
    • 2
    • 4
  • l

    Lukas Lechner

    01/08/2021, 12:51 PM
    New Blogpost: “7 Common Mistakes you might be making when using Kotlin Coroutines” => https://www.lukaslechner.com/7-common-mistakes-you-might-be-making-when-using-kotlin-coroutines/
    🙌🏻 3
    n
    • 2
    • 1
  • a

    Ayomide

    01/09/2021, 6:01 PM
    Hey, I'm trying out Ktor's WebSocket client library. It returns incoming messages from a web socket as a 
    SharedFlow
     - I'm trying to figure out how to keep the web socket session (
    DefaultClientWebSocketSession
    ) running in the background so that I can collect the 
    SharedFlow
     messages and display them on screen as they stream in. I tried using 
    coroutineScope.launch{}
      but it seems like the web socket session would stop as soon as the coroutine scope block ended. Not sure what to do to make sure the process runs forever in the background
    r
    • 2
    • 4
  • t

    timrijckaert

    01/10/2021, 4:51 PM
    Does anybody know how you can create a
    MutableStateFlow
    that allows duplicate events to be send. Basically mitigate the default
    distinctUntilChanged
    behavior?
    b
    u
    • 3
    • 7
Powered by Linen
Title
t

timrijckaert

01/10/2021, 4:51 PM
Does anybody know how you can create a
MutableStateFlow
that allows duplicate events to be send. Basically mitigate the default
distinctUntilChanged
behavior?
b

bezrukov

01/10/2021, 4:56 PM
Use SharedFlow instead, there is no way to do this with stateflow idiomatically (there is an ugly way though - via object wrapper, but even in this case some items may be lost if collector is slower than producer)
✅ 1
t

timrijckaert

01/10/2021, 5:00 PM
Can you give a simple sample of the
SharedFlow
that allows duplicate events?
b

bezrukov

01/10/2021, 5:16 PM
Yep, something like
MutableSharedFlow<Event>(1, extraBufferCapacity = 64)
👍 1
u

ursus

01/10/2021, 8:41 PM
wait what? if I stateFlow.value = "5" twice, it will get emitted only once?
b

bezrukov

01/10/2021, 8:45 PM
yes, because it represents "state" (obviously from its name) when you set it to "5" second time, state was not changed
☝️ 1
u

ursus

01/10/2021, 9:10 PM
debatable, but okay
+ equals can be heavy ..a waste for collections, etc near UI especially, which will get diffed anyways
View count: 3