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

    myanmarking

    03/17/2020, 1:07 PM
    i want to use it like flowOf<Int>().onEmpty{ emit(0) }, sth like this
    s
    a
    • 3
    • 2
  • d

    dave08

    03/17/2020, 2:42 PM
    If I use
    asFlow()
    on a closed
    ConflatedBroadcastChannel
    will it receive the latest element sent before it was closed, or will the flow be empty?
    e
    • 2
    • 17
  • d

    dave08

    03/17/2020, 2:44 PM
    In general, even if not closed, it seems like it misses the elements sent before the
    asFlow()
    was run on it...
    l
    • 2
    • 1
  • m

    Maciek

    03/17/2020, 2:57 PM
    Hey guys, I want to send stream of data from one class to the other (adapter/viewholder to activity). Previously I'd use RxJava's Subject for it, what would be recommended way of achieving this with flow? I see how I could do it with channels but it's hard for me to wrap my head around the flow for such use cases Should I use something like this?
    Untitled.kt
    v
    • 2
    • 1
  • v

    Vsevolod Tolstopyatov [JB]

    03/17/2020, 3:21 PM
    📣 📣 📣 kotlinx.coroutines 1.3.5 is here! •
    Flow.firstOrNull
    operators •
    java.time
    and
    kotlin.time.Duration
    adapters • More performant and configurable
    DebugProbes
    for usages in production environment •
    kotlin-coroutines-jdk9
    module for integration with
    java.util.concurrent.Flow
    • Various bug fixes and improvements Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.3.5
    🎉 25
    a
    • 2
    • 1
  • m

    myanmarking

    03/17/2020, 3:32 PM
    what is the proper way of transforming a flow<List<T>> to a flow<T> ?
    s
    a
    d
    • 4
    • 8
  • s

    Slackbot

    03/18/2020, 1:11 AM
    This message was deleted.
    o
    s
    • 3
    • 3
  • j

    Jérôme Gully

    03/18/2020, 11:22 AM
    Hi, i'm making a class that check audio input level in Android, for do that I must call one method each 100ms in a separate thread and notify the value with a lambda
    block
    , for the moment I have this (old school hava style) and I guess I can do better with coroutines.
    mustStopThread
    is a boolean that is false when class is created and true when I must stop the check (when I quit the activity). What I can do better ?
    init {
        Thread(Runnable {
            while (!mustStopThread) {
                val lastMaxSoundLevel: Int = mediaRecorder.maxAmplitude
                block.invoke(lastMaxSoundLevel)
                Thread.sleep(100)
            }
        }).start()
    }
    😒uspend: 2
    e
    • 2
    • 4
  • o

    Orhan Tozan

    03/18/2020, 6:56 PM
    Given the following viewmodel:
    class ViewModel {
        val selectedColor: Flow<Color> = ...
        fun onNewColorSelect(newColor: Color) {
            ...
        }
    }
    How can the
    onNewColorSelect
    method update the
    selectedColor
    flow? With Android, you would use
    MutableLiveData
    . How would you solve this problem with Flow?
    z
    • 2
    • 18
  • p

    PHondogo

    03/18/2020, 7:53 PM
    Hello! Is there any possibility to run test in supend test function?
    class Test{
      @Test
      suspend test() {
        // test logic with suspend calls
      }
    }
    d
    j
    • 3
    • 2
  • o

    Orhan Tozan

    03/18/2020, 10:16 PM
    In my ViewModel, when an event listener is triggered:
    onUserSelect(userId: Int)
    I want it to offer an event to a broadcastchannel named
    userSelectEvents: BroadCastChannel<UserSelectEvent>
    . The flow
    selectedUsers
    should depend on this, so I'm probably looking to some kind of building a reducer. This is my idea, is it good?
    z
    • 2
    • 16
  • r

    Rômero Ricardo

    03/19/2020, 4:03 AM
    Hi folks, Can any of you show me what's the recomended way of scheduling a (async) task to happen in X minutes from current time? If possible in such a way that I can control executors. Thanks in advance.
    o
    • 2
    • 1
  • m

    Mikołaj Kąkol

    03/19/2020, 7:14 AM
    hi, if I'm given a
    scope
    called
    bigScope
    how can I create a scope
    smallScope
    that will be canceled when
    bigScope
    is cancelled?
    o
    • 2
    • 8
  • o

    Orhan Tozan

    03/19/2020, 2:35 PM
    Given the following:
    private val _selectedUserIds = ConflatedBroadcastChannel<List<Int>>(emptyList())
    private val selectedUserIds: Flow<List<Int>> = _selectedUserIds.asFlow()
    A
    onSaveButtonClick()
    method inside the class should send a network call with the value of selectedUserIds Should I get it's value by using the
    .value
    of the
    ConflatedBroadcastChannel
    or should I launch a coroutine and call
    .collect()
    on the
    Flow
    ? What's the difference?
    k
    • 2
    • 62
  • j

    JP

    03/20/2020, 12:16 PM
    fun main() = runBlocking { // this: CoroutineScope
    
        coroutineScope { // Creates a coroutine scope
            println(this)
            println(this@runBlocking)
    ...
    and the printed result is:
    "coroutine#1":ScopeCoroutine{Active}@64a294a6
    "coroutine#1":BlockingCoroutine{Active}@7e0b37bc
    Why do they have the same name “coroutine#1”? If they are different coroutines, shouldn’t they have different labels? Am I missing something?
    f
    e
    • 3
    • 4
  • j

    JP

    03/20/2020, 2:29 PM
    I’d like to ask if I understood this correct: https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#cancellation-is-cooperative
    import kotlinx.coroutines.*
    
    fun main() = runBlocking {
        val startTime = System.currentTimeMillis()
        val job = launch(Dispatchers.Default) {
            var nextPrintTime = startTime
            var i = 0
            while (i < 5) { // computation loop, just wastes CPU
                // print a message twice a second
                if (System.currentTimeMillis() >= nextPrintTime) {
                    println("job: I'm sleeping ${i++} ...")
                    nextPrintTime += 500L
                }
            }
        }
        delay(1300L) // delay a bit
        println("main: I'm tired of waiting!")
        job.cancelAndJoin() // cancels the job and waits for its completion
        println("main: Now I can quit.")
    }
    The output is:
    [DefaultDispatcher-worker-1 @coroutine#2] job: I'm sleeping 0 ...
    [DefaultDispatcher-worker-1 @coroutine#2] job: I'm sleeping 1 ...
    [DefaultDispatcher-worker-1 @coroutine#2] job: I'm sleeping 2 ...
    [main @coroutine#1] main: I'm tired of waiting!
    [DefaultDispatcher-worker-1 @coroutine#2] job: I'm sleeping 3 ...
    [DefaultDispatcher-worker-1 @coroutine#2] job: I'm sleeping 4 ...
    [main @coroutine#1] main: Now I can quit.
    From my understanding, the
    job
    did not get cancelled despite the
    job.cancelAndJoin()
    call, because there is no suspending functions (e.g.
    delay
    ) which are cancellable (checks for cancellation cooperatively). Therefore the job completes after five iterations, then the
    job.join()
    returns, and then at last “main: Now I can quit.” is printed. Is this correct? P.S. Does “every” suspending function always check for cancellation?
    a
    u
    j
    • 4
    • 6
  • k

    kevin.cianfarini

    03/20/2020, 3:20 PM
    Simple question... will corotuines launched in a dispatcher that's backed by a thread pool implicitly be parallelized? Eg.
    suspend fun foo() = withContext(Dispatchers.Default) {
        for (1..100) {
            async { ... }
        }
    }
    Will that be bound to a single thread or will is try to spread the workload?
    s
    z
    l
    • 4
    • 14
  • l

    liminal

    03/20/2020, 9:20 PM
    Any ideas why this test fails https://github.com/jshvarts/FlowChannels101/blob/master/app/src/test/java/com/example/coroutines/views/UserDetailViewModelTest.kt#L100 with
    Wanted but not invoked observer.onChanged...no interactions with this mock
    . Thanks in advance!
    • 1
    • 4
  • r

    Raphael Almeida

    03/21/2020, 5:16 PM
    Is there any way to throtle the messages to a channel? Adding delay to the messages given a param of the msg. Linke a priority queue or delayed queue? I though to just run a coroutine and then delay but it seems no good for a fan out scenario.
    z
    • 2
    • 6
  • j

    JP

    03/22/2020, 6:22 AM
    I was reading the documentation https://kotlinlang.org/docs/reference/coroutines/select-expression.html, and when I tried to execute the code
    import kotlinx.coroutines.*
    import kotlinx.coroutines.channels.*
    import kotlinx.coroutines.selects.*
    
    suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String =
        select<String> {
            a.onReceiveOrNull { value -> 
                if (value == null) 
                    "Channel 'a' is closed" 
                else 
                    "a -> '$value'"
            }
            b.onReceiveOrNull { value -> 
                if (value == null) 
                    "Channel 'b' is closed"
                else    
                    "b -> '$value'"
            }
        }
        
    fun main() = runBlocking<Unit> {
        val a = produce<String> {
            repeat(4) { send("Hello $it") }
        }
        val b = produce<String> {
            repeat(4) { send("World $it") }
        }
        repeat(8) { // print first eight results
            println(selectAorB(a, b))
        }
        coroutineContext.cancelChildren()        
    }
    The compiler gave warning that
    onReceiveOrNull
    was deprecated:
    'onReceiveOrNull: SelectClause1<E?>' is deprecated. Deprecated in favor of onReceiveOrClosed and onReceiveOrNull extension
    I guess this is not yet applied in the guide from the documentation. May I ask how I should change the code?
    suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String =
        select<String> {
            a.onReceiveOrClosed {  
                if (it.isClosed)
                    "Channel 'a' is closed"
                else
                    "a -> '${it.value}'"
            }
            b.onReceiveOrClosed { 
                if (it.isClosed)
                    "Channel 'b' is closed"
                else
                    "b -> '${it.value}'"
            }
        }
    Would this be the preferred way for now?
    t
    • 2
    • 1
  • c

    Chills

    03/22/2020, 6:38 AM
    when i was using threads used to work on concurrentlinkedqueue and others is there any equivalent for it in kotlin when using coroutines?
    k
    z
    • 3
    • 3
  • f

    fcosta

    03/23/2020, 2:32 PM
    Can we expect coroutines in K/N in 1.4? https://blog.jetbrains.com/kotlin/2020/03/kotlin-1-4-m1-released/
    👀 3
    j
    r
    e
    • 4
    • 9
  • h

    heyitsmohit

    03/23/2020, 7:23 PM
    My team and I found some issues around using coroutines. Just wanted to surface them here. If you are experiencing the same issues, please up-vote. https://youtrack.jetbrains.com/issue/KT-36660 https://youtrack.jetbrains.com/issue/KT-37456
    s
    d
    • 3
    • 3
  • k

    kevin.cianfarini

    03/23/2020, 8:15 PM
    how do I cancel the children a coroutinescope and not the scope itself?
    d
    o
    +3
    • 6
    • 39
  • m

    Maciek

    03/24/2020, 6:55 AM
    is there a way to wait for not yet started coroutine? I want to achieve something similar to
    yield
    but with the coroutine that'll be started in the future
    o
    s
    b
    • 4
    • 10
  • l

    luke_c

    03/24/2020, 10:41 AM
    Hiya, on my splash screen (android) I want to fetch some remote config in the background, then only move on from the screen once the fetch has completed (either successfully or via exception, I don’t care) I have a private field that should launch immediately upon the class being instantiated
    private val remoteConfigFetch = lifecycleScope.launch { FirebaseRemoteConfig.init() }
    Then further on before the splash screen finally moves on I’m calling join
    private fun continueToApp() = runBlocking {
        remoteConfigFetch.join()
        goToMainActivity()
    }
    Is this the correct approach? Initially I thought about using async but figured because I don’t care about whether it fails or errors and don’t care about the result it was better to use launch?
    a
    • 2
    • 8
  • g

    Gin Wang

    03/24/2020, 6:05 PM
    Hello, is
    Channel
    still preferred over
    Flow
    for use cases that involve multiple emitters/listeners for a data stream? From what I've read online, Flow is meant to be a safer alternative to Channel, but seems best used for one to one communication?
    t
    z
    • 3
    • 6
  • s

    Sam Garfinkel

    03/24/2020, 6:27 PM
    I’m sure this should be obvious, but given an existing synchronous API that expects a blocking
    InputStream
    or
    Reader
    , what’s the correct way to wrap that such that I can call it as a suspendable function and map some sort of asynchronous communication such as a
    Channel
    into the given
    InputStream
    ?
    k
    • 2
    • 6
  • o

    Orhan Tozan

    03/25/2020, 4:00 AM
    In a multi-module project, should a kotlin module that exposes Flow as its public api, specify its coroutines dependency as
    api
    instead of
    implementation
    ? Also if so, does this also mean for target dependencies (e.g. commonMain:
    api(coroutines-core-common)
    and jvmMain:
    api(coroutines-core)
    )
    o
    t
    • 3
    • 3
  • p

    paulex

    03/25/2020, 8:16 AM
    Please, Without using Android, is there a way i can switch context to a main thread inside a launch {} ?
    o
    t
    z
    • 4
    • 14
Powered by Linen
Title
p

paulex

03/25/2020, 8:16 AM
Please, Without using Android, is there a way i can switch context to a main thread inside a launch {} ?
o

octylFractal

03/25/2020, 8:18 AM
it is the same way as on android -- unless you're not using JavaFX/Swing/etc., and in that case you would need to implement the MainDispatcher yourself to indicate to Kotlin which thread is your "main" thread
p

paulex

03/25/2020, 8:30 AM
Yeah, i'm neither using JavaFX or Swing... can you guide me on how to implement a main dispatcher perhaps a link will help.
@octylFractal
t

tseisel

03/25/2020, 8:31 AM
Since you can't dispatch back to the first thread (the thread that called the
main
function) on non-UI application due to the lack of an event loop, you could use
newSingleThreadContext()
to create a dispatcher to use as your main thread. Note that you'll have to block the first thread (with
runBlocking
and
withContext
, or using
launch
and awaiting on the resulting job), otherwise the program will terminate.
o

octylFractal

03/25/2020, 8:39 AM
https://gist.github.com/octylFractal/4fb0ff0fe7fb25cb26d173ba1b3fcbf1 is a small + quick sample for a main dispatcher that does dispatch back to the main thread
only issue being that it doesn't quit 😛 you probably already have some sort of event loop with an exit flag you can put in place of the
while
loop though
p

paulex

03/25/2020, 8:47 AM
Alright... That made me feel like a dummy 🤦‍♂️ . I'm disappointed at my efforts in coding, like how did you come up with that so quick, how did you know about
ArbitraryMainDispatcher
etc... What am i not reading right?
@octylFractal
o

octylFractal

03/25/2020, 8:49 AM
well, I just wrote
ArbitraryMainDispatcher
based on the
JavaFX
main dispatcher, and gave it
queue(Runnable)
as a stand-in for JavaFX's
Platform.runLater(Runnable)
. The main part is knowing that
MainCoroutineDispatcher
exists
p

paulex

03/25/2020, 8:51 AM
Alright, followed you on keybase.! thanks
👍 1
t

tseisel

03/25/2020, 8:53 AM
Don't feel bad about it @paulex, I thought I knew a lot about coroutines until I saw @octylFractal's answer. Let's learn from each other!
👍 1
💪 1
🤣 2
🤗 2
z

Zach Klippenstein (he/him) [MOD]

03/25/2020, 3:14 PM
The coroutines library already provides a binding of
Dispatchers.Main
for javafx, is there some reason you can't use that? https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/kotlinx-coroutines-javafx/README.md
o

octylFractal

03/25/2020, 8:21 PM
because they're not using JavaFX: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1585125021004100
z

Zach Klippenstein (he/him) [MOD]

03/25/2020, 9:40 PM
Oops, I missed the “neither”, my bad
View count: 2