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

    diesieben07

    11/17/2020, 2:36 PM
    I want to share a
    Flow
    between a fixed number of collectors. Currently I just do
    data.shareIn(this, SharingStarted.Lazily)
    . Then I let all the collectors colllect that shared flow. However there is a race condition here. In theory the following can happen: • first collector starts collecting, this starts the sharing • the emitter emits things and they are immediately consumed by the already subscribed first collector. • the rest of the collectors start collecting, but they missed out on the first values. I could set
    replay
    to some number, but that's just a stopgap. Is there a way to say "okay, sharing coroutine, you can start dropping things now, there won't be any further subscribers" after all the subscribers are there?
    w
    d
    +1
    12 replies · 4 participants
  • l

    Lulu

    11/17/2020, 3:32 PM
    I have a
    Flow
    of requests that need to be processed by (many) different workers, and I was wondering which option is better from the following: 1. Have each worker apply
    filter {  }
    on the main
    Flow
    to check if this request belongs to it. 2. Have a separate
    Flow
    for each worker, and a general worker that checks all the main `Flow`'s requests and re-emit each request to the corresponding worker's
    Flow
    . 3. (possibly something I haven't thought of?)
    d
    s
    +1
    12 replies · 4 participants
  • d

    diesieben07

    11/17/2020, 6:21 PM
    I can share ("fan-out") a Flow between multiple collectors while only collecting the original flow once using
    shareIn
    . However this does not support a finite flow, as
    shareIn
    makes the flow endless ("Shared flow never completes"). How can the collectors of the shared flow ever complete? Even if the original flow completes, they will continue to "hang", expecting more elements, because the shared flow never completes.
    z
    l
    5 replies · 3 participants
  • a

    Aaron Todd

    11/17/2020, 7:50 PM
    if I have a background/worker coroutine that is processing tasks like so
    1 suspend fun processTasks(chan: ReceiveChannel<MyTask>) {
    2    for(task in chan) {
    3        doWork() // non-suspend function
    4    }
    5 }
    is it correct to say that on Line 3 once the coroutine is running on a thread it will not suspend again and potentially switch threads until the next call to
    chan.receive()
    on line 2? More generically the only time a coroutine has a chance to suspend is at a suspension point which is defined by a
    suspend
    function call? (i.e. no instruction level suspension possible)
    z
    2 replies · 2 participants
  • z

    zsperske

    11/18/2020, 2:56 AM
    Can anyone help me understand the use case difference for a
    callbackFlow
    and a
    Channel
    ? both seem to support "hot" streams
    l
    z
    4 replies · 3 participants
  • t

    Tolriq

    11/18/2020, 7:40 AM
    Documentation of SharedFlow says:
    All methods of shared flow are *thread-safe* and can be safely invoked from concurrent coroutines without external synchronization.
    But IDE on SharedFlow.emit says:
    Collects the value emitted by the upstream. This method is not thread-safe and should not be invoked concurrently.
    Which one is right?
    e
    7 replies · 2 participants
  • s

    solidogen

    11/18/2020, 12:20 PM
    I have a ArrayBroadcastChannel, which I subscribe to like channel.asFlow().launchIn(scope) between launchIn <-> flow.onStart is about 100-150ms so all items I emit in those 150ms are lost can I subscribe to this channel in some blocking way, so every emit after launchIn would be collected? I’m currently tied to coroutines 1.3.9 because of other dependencies, also Conflated channel is redundant in my case
    e
    z
    4 replies · 3 participants
  • d

    Davide Giuseppe Farella

    11/18/2020, 1:42 PM
    Hello, is there an easy way to convert a
    Flow
    to a
    StateFlow
    on the fly? ( i.e.
    flow.asStateFlow()
    )
    j
    9 replies · 2 participants
  • r

    Rolbin

    11/18/2020, 2:11 PM
    Hello, I was reading about coroutines and I came across this in an SO answer. "when you execute 1,000,000 concurrent routines, it doesn't have to create 1,000,000 threads" Let's say, these many routines run on just 4 threads. In that case it's same as that of a fixed thread pool of size 4 ?
    a
    z
    3 replies · 3 participants
  • s

    Slackbot

    11/18/2020, 2:18 PM
    This message was deleted.
    z
    1 reply · 2 participants
  • b

    bbaldino

    11/18/2020, 4:51 PM
    I have a few subcomponents, each which have a state. From the 'parent' component, I want to monitor the state changes of the subcomponents and, if any of them go to an error state, take some action. I was hoping to be able to do a
    select
    expression in the 'parent' on a set of
    StateFlows
    from the subcomponents, but I saw
    onReceive
    isn't directly supported by
    StateFlow
    . I tried using
    produceIn
    on the
    StateFlow
    so I could use
    onReceive
    , but then I get the most recent state over and over. I looked at using
    distinctUntilChanged
    on the
    StateFlow
    , but then saw that has no effect...What should I go with here? I also can't 'miss' a value here, so maybe
    StateFlow
    is the wrong tool?
    2 replies · 1 participant
  • d

    doodla

    11/18/2020, 8:18 PM
    Given a block -
    var x: Int = 0
    
    suspend fun modifyX() {
        if (x > 10) {
            x -= 1
        } else {
            x += 1
        }
    }
    
    fun main() {
        runBlocking {
            withContext(<http://Dispatchers.IO|Dispatchers.IO>){
                repeat(10) {
                    modifyX()
                }
            }
        }
    }
    Does
    x
    need to be
    @Volatile
    ?
    z
    7 replies · 2 participants
  • d

    df

    11/18/2020, 8:40 PM
    hey there. I have a list of a few million urls and i want to fetch the head response for them. What would be the best approach if I want to limit the amount of urls that can be fetched concurrently? Of course I could have a sequence that produces the requests, chunk them and process one chunk at a time but this feels like my default coming-from-a-java-world solution instead of something tailored to kotlin / around co-routines.
    j
    b
    4 replies · 3 participants
  • c

    coroutinedispatcher

    11/18/2020, 10:31 PM
    Didn’t find much in Google about this. I am trying to test this function which uses
    SharedFlow
    but I am getting an
    IllegalStateException: This job has not completed yet
    . It’s basically pretty easy because I commented out the rest of the code for now:
    fun registerNewUser(email: String, password: String, hint: String) {
            viewModelScope.launch { _state.emit(State.Loading) }
            // commented out for the moment just to make sure it's not the rest of the code that is failing the test
        }
    And the test:
    @Test
        fun `starting registration process will set the state immediately to loading`() =
            runBlockingTest(testCoroutineDispatcher) {
                registerViewModel.registerNewUser("anyEmail", "anyPassword", "anyHint")
    
     ~           assertEquals(registerViewModel.state.first(), RegisterViewModel.State.Loading)
            }
    Versions:
    coroutines: "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1",
                coroutines_android : "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1",
                coroutines_test: "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.1"
    Probably doing something wrong, but not sure what. Any ideas/input?
    2 replies · 1 participant
  • y

    yschimke

    11/19/2020, 10:03 AM
    I just deleted a driveby PR comment that should either be a tweet into the ether or a slack question, so here 'tis. Is CancellableContinuation.resume's handling of a cancellation lambda an example where it's less readable? I love Kotlin's last param lambda logic generally. I think in this API, this callsite is an example of where it hides the intent.
    cont.resume(Unit) { unlock(owner) }
    vs
    cont.resume(Unit, onCancellation = { unlock(owner) })
    t
    1 reply · 2 participants
  • e

    elizarov

    11/19/2020, 3:00 PM
    📣
    kotlinx-coroutines
    version
    1.4.1-native-mt
    released (with multithreading in Kotlin/Native)
    :kotlin-intensifies: 42
    🎉 47
    t
    p
    6 replies · 3 participants
  • c

    christophsturm

    11/20/2020, 11:07 AM
    why does
    Publisher<T>.asFlow()
    not support nullable values? https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-reactive/kotlinx.coroutines.reactive/org.reactivestreams.-publisher/as-flow.html
    e
    2 replies · 2 participants
  • m

    Mohamed Ibrahim

    11/20/2020, 12:27 PM
    Hello there, if
    repositoryContract.retrieveTopStories()
    is a suspend function which returns
    List<Story>
    why I can’t convert it to Flow by calling
    repositoryContract.retrieveTopStories().asFlow()
    j
    e
    +2
    5 replies · 5 participants
  • w

    why

    11/20/2020, 1:26 PM
    Hi.. I want to use mutex.withLock{...} but it requires ‘suspend’ keyword which is a breaking change, how can I achieve the same effect (like synchronized in java) without leaking/changing my fun def? (KMP btw)
    r
    8 replies · 2 participants
  • c

    christophsturm

    11/20/2020, 3:46 PM
    how can i add throttling to a code like this:
    (0 until entries).map {
                        async {
                            repo.create(connection, user)
                        }
                    }.forEach { it.await() }
    t
    c
    11 replies · 3 participants
  • n

    Nemanja Mladenović

    11/20/2020, 5:15 PM
    Can someone explain how to convert live data to state flow in this situation: - livedata2 is map of another livedata1 in vm and there are 2 observers in ui layer, one observes original livedata1, and other observes mapped livedata2 What I discovered is that simply converting live data to state flow is not working as expected. Map is converting state flow to flow and not state flow. Second I cannot get both flows to trigger collect when collect are written as part of the same scope in ui layer. Any resource on the subject?
    1 reply · 1 participant
  • l

    Lulu

    11/20/2020, 7:20 PM
    I'm not sure if this is the right place to ask but is it on the roadmap to support a concurrent hash map in Kotlin common? It's very important for our multiplatform project and we didn't like 3rd party libraries.
    e
    c
    2 replies · 3 participants
  • j

    John O'Reilly

    11/21/2020, 11:22 AM
    Am using
    StateFlow
    in view model (along with use of
    stateIn
    )....is there something equivalent to
    MediatorLiveData
    or
    switchMap
    when using that?
    j
    j
    +1
    9 replies · 4 participants
  • s

    Sivan

    11/22/2020, 11:43 AM
    I am using
    Flow
    with
    suspend functions
    to read a stream of data from my API. To get all the registered users,
    flow
    seems like a cool option. But while creating a user which is a one-shot function, would flow really come in handy? I really like the idea of emitting streams by passing a Result wrapper around the data and this gives me more clarity and readability in code. Just want to know if it is considered as best practice to use Flow for one shot functions like creating a user or does it become unnecessary?
    l
    2 replies · 2 participants
  • d

    df

    11/22/2020, 6:55 PM
    Why do all methods in the docs for producing functions extend CoroutineScope? Is that just a convention or does it serve a special purpose?
    e
    3 replies · 2 participants
  • p

    Paul Woitaschek

    11/23/2020, 7:46 AM
    Are there any articles available on Shared Flow and error handling? I have a common use case that I want to share a network call but want new consumers no trigger the upstream flow when subscribed after an error.
    n
    w
    22 replies · 3 participants
  • s

    samuel

    11/23/2020, 12:41 PM
    i am curious if there is a better way to run a “fireAndForget” action on the items in a flow as an intermediary step e.g in a repository
    suspend inline fun <T>Flow<T>.fireAndForget(crossinline block: (T) -> Unit): Flow<T> {
        coroutineScope {
            launch {
                runCatching {
                    collect {
                        block(it)
                    }
                }
            }
        }
        return this
    }
    f
    b
    6 replies · 3 participants
  • l

    Lulu

    11/23/2020, 11:45 PM
    We're trying to perform some tasks sequentially and i was wondering if an actor or a Mutex is better suited for this case. There'd be many queues and each of them will be processing few tasks.
    z
    16 replies · 2 participants
  • t

    tateisu

    11/24/2020, 2:22 AM
    Is there a way to poll a single element from Flow, like Channel.receive ()? I want to poll the data inside a recursive parser function instead of always receiving the data in the same lambda.
    g
    11 replies · 2 participants
  • t

    tateisu

    11/24/2020, 3:01 AM
    it's Flow<T>.produceIn()
    g
    1 reply · 2 participants
Powered by Linen
Title
t

tateisu

11/24/2020, 3:01 AM
it's Flow<T>.produceIn()
g

gildor

11/24/2020, 4:19 AM
It just creates Channel
View count: 4