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

    Daniel

    07/10/2020, 6:48 PM
    Hey everyone, I wrote a project that uses flow with mvi architecture You can check it out here https://github.com/Ezike/Baking-App-Kotlin
    🎉 6
    h
    s
    3 replies · 3 participants
  • a

    andylamax

    07/11/2020, 4:41 AM
    Does calling
    cancel
    on a
    CoroutineScope
    preven't it from launching coroutines in the near future?
    o
    2 replies · 2 participants
  • t

    Tim Malseed

    07/11/2020, 5:32 AM
    I’ve got a function like so:
    suspend fun getAudio(songId: Long): AudioStream? {
            return withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                songRepository.getSongs(SongQuery.SongIds(listOf(songId))).firstOrNull()?.firstOrNull()?.let { song ->
                    val uri = Uri.parse(song.path)
                    if (song.path.startsWith("content://")) {
                        if (DocumentsContract.isDocumentUri(context, uri)) {
                            val documentFile = DocumentFile.fromSingleUri(context, uri)
                            documentFile?.let {
                                context.contentResolver.openInputStream(documentFile.uri)?.let { inputStream ->
                                    AudioStream(inputStream, documentFile.length(), documentFile.type ?: "audio/*")
                                }
                            }
                        } else {
                            context.contentResolver.openInputStream(uri)?.let { inputStream ->
                                AudioStream(inputStream, song.size, song.mimeType)
                            }
                        }
                    } else {
                        AudioStream(File(uri.toString()).inputStream(), song.size, song.mimeType)
                    }
                }
            }
        }
    AS complains that
    openInputStream()
    is an ‘inappropriate blocking call’ Is this a false positive by AS, or am I doing something wrong here?
    e
    m
    3 replies · 3 participants
  • l

    louiscad

    07/11/2020, 6:38 PM
    Hello, did you ever forget to activate/collect a
    Flow
    ? If so, please react with ➕. I personally did (and that made a minor bug reach production), so I submitted a feature request: https://youtrack.jetbrains.com/issue/KT-40228
    ➕ 13
    p
    r
    3 replies · 3 participants
  • i

    iex

    07/12/2020, 4:59 PM
    Hi! How do I make this compile?
    private suspend fun myStruct(): MyStruct = MyStruct(1) {
        foo()
    }
    
    suspend fun foo() {}
    
    private data class MyStruct(
        val a: Int,
        val callback: (() -> Unit)?
    )
    a
    s
    +1
    9 replies · 4 participants
  • i

    iex

    07/12/2020, 5:24 PM
    Why is it necessary to call
    BroadcastChannel.send
    in a suspended function? With e.g. RxJava pushing events to a subject doesn't require anything special.
    l
    j
    +2
    60 replies · 5 participants
  • i

    immathan

    07/13/2020, 2:05 PM
    Hello ✋ , I have an use-case where I need to implement a
    backoff
    strategy using the flow.
    fun main() {
        runBlocking {
            (0..8).asFlow()
                .flatMapConcat { input ->
                    // To simulate a flow which fetches data based on a time-window which is exponentially increased if there's no data
                    // available with in that time frame.
                    flow {
                        println("Input: $input")
                        if (input < 5) {
                            emit(emptyList<String>())
                        } else { // After emitting this once the flow should complete
                            emit(listOf("Available"))
                        }
                    }.retryWhenThrow(DummyException(), predicate = {
                        it.isNotEmpty()
                    })
                }.collect {
                    //println(it)
                }
        }
    }
    
    class DummyException : Exception("Collected size is empty")
    
    private inline fun <T> Flow<T>.retryWhenThrow(
        throwable: Throwable,
        crossinline predicate: suspend (T) -> Boolean
    ): Flow<T> {
        return flow {
            collect { value ->
                if (!predicate(value)) {
                    throw throwable // informing the upstream to keep emitting since the condition is met
                }
                println("Value: $value")
                emit(value)
            }
        }.catch { e ->
            if (e::class != throwable::class) throw e
        }
    }
    If you run this example in kotlin play ground you will notice that the flow keep emitting the value even after my condition is met(Where the list is not empty anymore). After much digging I found that I need something like takeUntil from rxJava. I need some help how I should proceed this.
    m
    j
    12 replies · 3 participants
  • j

    julian

    07/14/2020, 6:36 PM
    What's the best way to flatten a
    Flow<Flow<T>>
    to
    Flow<T>
    ?
    j
    z
    3 replies · 3 participants
  • j

    julian

    07/14/2020, 8:01 PM
    For some reason I can't do this in my project
    val f: Flow<Int> = flow<Int> { emit(1) }.transform<Int, Int> { emit(it) }
    When I compile, I get
    Error:(6, 32) Kotlin: Unresolved reference: transform
    Error:(10, 47) Kotlin: Unresolved reference: transform
    Error:(10, 69) Kotlin: Unresolved reference: emit
    Error:(10, 74) Kotlin: Unresolved reference: it
    So I set up a new project with the same dependency on
    kotlinx-coroutines-core:1.3.7
    . That works fine. Also, oddly, all my other flow-related code that doesn't use
    transform
    is fine. Has anyone else encountered this before?
    d
    m
    7 replies · 3 participants
  • m

    matthew graf

    07/14/2020, 10:39 PM
    When testing suspend functions, does anyone have advice on whether to use
    runBlockingTest
    vs
    runBlocking
    ?
    runBlockingTest
    seems to have some nice features, but this line in the documentation makes it sound like there is some risk of deprecation
    This API is experimental and it is may change before migrating out of experimental (while it is marked as @ExperimentalCoroutinesApi). Changes during experimental may have deprecation applied when possible, but it is not advised to use the API in stable code before it leaves experimental due to possible breaking changes.
    g
    2 replies · 2 participants
  • l

    Luis Munoz

    07/15/2020, 1:30 AM
    Hey guys how do run flows concurrently then collect the output
    @Test
        fun `experimental`() {
            runBlocking {
                val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>) 
                val songs = listOf("a", "b", "c", "d", "e")
                songs.asFlow().flatMapMerge {
                    requestFlow("${Thread.currentThread().name} $it check")
                }
                .collect {
                    println("$it")
                }
            }
        }
    
        fun requestFlow(i: String): Flow<String> = flow {
            emit("$i: First")
            Thread.sleep(1000)
            emit("$i: Second")
        }
    o
    j
    +1
    17 replies · 4 participants
  • h

    handstandsam

    07/15/2020, 2:28 PM
    Wanted to share the slides for my presentation
    Kotlin Actors - No Drama Concurrency
    https://speakerdeck.com/handstandsam/kotlin-actors-no-drama-concurrency
    👍 9
    j
    m
    +2
    7 replies · 5 participants
  • a

    Astronaut4449

    07/15/2020, 3:30 PM
    How do you document that the
    async
    -coroutine-builder of the kotlinx.coroutines library can throw exceptions since the coroutine builder itself does not throw an exception but the
    .await()
    does?
    /**
     * @throws[IllegalStateException] ... <- would this be correct?
     */
    fun CoroutineScope.doStuffAsync() = async { ... }
    l
    e
    +1
    7 replies · 4 participants
  • t

    Tamas

    07/15/2020, 5:38 PM
    hello guys, I am fighting with intellij and coroutines. I try to use
    produce
    I have imported it from
    import kotlinx.coroutines.channels.produce
    but the ide still displays it red, and says
    create function
    on alt-enter. my dependencies are
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
        implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-jdk9:1.3.7'
        implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-javafx:1.3.7'
    o
    a
    18 replies · 3 participants
  • t

    Tim Malseed

    07/16/2020, 3:37 AM
    I’ve got the following code (Android):
    coroutineScope.launch {
        val songs = mutableListOf<Song>()
        mediaProvider.findSongs().collect { (song, progress) ->
            songs.add(song)
            listeners.forEach { listener -> listener.onProgress(progress, song) }
        }
    
        listeners.forEach { listener -> listener.onComplete() }
    }
    The scope is instantiated via
    CoroutineScope(Dispatchers.Main)
    Despite
    listener.onProgress
    being called on the main thread - and successful log messages when it is called, the UI updates I’m making in response don’t seem to have any effect. Are the
    listener.onProgress(progress, song)
    calls somehow being gathered up and then all executed at the end? Ooh I think I might be blocking the main thread somewhere
    o
    5 replies · 2 participants
  • j

    Justin

    07/16/2020, 4:41 AM
    Will contracts be non-experimental in 1.4? What will no longer be experimental in 1.4?
    o
    2 replies · 2 participants
  • t

    Tim Malseed

    07/16/2020, 6:29 AM
    I apologise for all these dumb questions, but anyway.. Why does this work:
    override fun loadData() {
            launch {
                songRepository.getSongs(SongQuery.Album(name = album.name, albumArtistName = album.albumArtist))
                    .collect { songs ->
                        this@AlbumDetailPresenter.songs = songs
                        view?.setData(songs)
                    }
            }
        }
    But this doesn’t:
    override fun loadData() {
            launch {
                songRepository.getSongs(SongQuery.Album(name = album.name, albumArtistName = album.albumArtist))
                    .collect { songs ->
                        this@AlbumDetailPresenter.songs = songs
                    }
                view?.setData(songs)
            }
        }
    o
    g
    +3
    98 replies · 6 participants
  • t

    TwoClocks

    07/16/2020, 7:53 PM
    How can I tell if any continuations are in the queue to be run, or if there is a job waiting in delay() etc?
    o
    107 replies · 2 participants
  • e

    elizarov

    07/16/2020, 9:59 PM
    📣
    kotlinx.coroutines
    version
    1.3.8
    is released. It is an incremental update with several bug-fixes, a few improvements, and a couple minor features (experimental). Change log is here: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.3.8
    ❤️ 8
    👍 1
    😒uspend: 7
    🎉 24
    g
    l
    4 replies · 3 participants
  • e

    enighma

    07/16/2020, 10:20 PM
    QQ: I have a Java API with a callback and I want to wrap that in a kotlin suspend function, so I can avoid callback hell What is the most idiomatic way to do that? One obvious solution is a Countdown latch, but I imagine there being something more elegant.
    o
    e
    6 replies · 3 participants
  • g

    Gabriel Feo

    07/17/2020, 12:40 AM
    Would this onEach work to keep the current state of the flow?
    private val state = MutableStateFlow(initialState)
    
       fun getState(events: Flow<Event>): Flow<State> =
            merge(
                state, 
                events.transformLatest {
                    emit(state.value.copy(...))
                    ...
                    emit(state.value.copy(...))
                }
            ).onEach { state.value = it }
    Think I'm missing something here, the second emit calling
    state.value
    gets the same value as the first one
    o
    j
    10 replies · 3 participants
  • t

    tjohnn

    07/18/2020, 4:37 AM
    StateFlow does not emit an updated object value if a property of the object is changed, is this the intentional design? Example:
    data class Count(var value: Int = 0)
    
    private val count = MutableStateFlow(Count())
    
    val newCount = count.value
    newCount.value++ // no emission though value is updated
    count.value = newCount // this does not emit either
    :yes: 4
    z
    m
    4 replies · 3 participants
  • g

    gumil

    07/18/2020, 11:04 AM
    Hello people, is it okay to make use of
    yield
    in production code? I rarely see it being used and only seen it used in tests. I wanted to know people's opinion if they ever used this function.
    d
    z
    5 replies · 3 participants
  • s

    Slackbot

    07/19/2020, 5:40 PM
    This message was deleted.
    🤯 3
    z
    i
    7 replies · 3 participants
  • a

    allan.conda

    07/20/2020, 10:51 AM
    I need some help. I have 2 unrelated useCases sharing a common dependency, I want them to share the execution of their dependency if that’s possible, because it’s critical that the dependency is only called once. Is there a way to do this nicely with coroutines?
    Untitled
    b
    2 replies · 2 participants
  • m

    Maciek

    07/20/2020, 11:50 AM
    I've got two deferred values. I want to wait for both, execute something after one of them completes and cancel the other one, not yet completed. What'd be the mechanism to achieve it?
    t
    k
    +2
    16 replies · 5 participants
  • g

    gsala

    07/20/2020, 2:05 PM
    In this post https://medium.com/@elizarov/structured-concurrency-anniversary-f2cc748b2401 by Elizarov, Roman mentions a use case which is very similar to a problem I have.
    In fact, there are valid use-cases where you have an entity with its own life-time, like a HTTP connection, and a client code in another module of your application making a request in its own scope. You should be able to easily combine them so that request is restricted to both life-times. Currently, this is cumbersome to implement.
    What's the right approach to combine two different scopes/lifecycles when launching a coroutine? In my case I have a BLE connection which creates a scope bound to the lifecycle of the connection, and I'd like a client to be able to launch a task to send a message, but also within the scope in which this client lives. This is for an Android project, so client would normally be a Fragment or ViewModel
    s
    2 replies · 2 participants
  • v

    Vincent Williams

    07/20/2020, 11:20 PM
    Hey stupid question but how do I use the new StateFlow? Im using kotlin version 1.3.72 but it doesnt seem to have StateFlow
    o
    a
    30 replies · 3 participants
  • d

    dorf

    07/20/2020, 11:32 PM
    Beginner here… Is it a typical pattern to pass around the coroutine scope as a parameter to my suspen functions?
    z
    o
    25 replies · 3 participants
  • r

    Rechee Jozil

    07/21/2020, 3:41 AM
    What's the idiomatic/proper way to perform some suspending side effect to a suspending function. Basically, within a suspending function, I'd like to perform some other suspending work, but I don't want to wait on it and I don't care if it fails (I'll just log). Here's a gist of how I'd like to do it: https://gist.github.com/recheej/387a0ea70552c0bff983b8028591f2cc
    o
    g
    3 replies · 3 participants
Powered by Linen
Title
r

Rechee Jozil

07/21/2020, 3:41 AM
What's the idiomatic/proper way to perform some suspending side effect to a suspending function. Basically, within a suspending function, I'd like to perform some other suspending work, but I don't want to wait on it and I don't care if it fails (I'll just log). Here's a gist of how I'd like to do it: https://gist.github.com/recheej/387a0ea70552c0bff983b8028591f2cc
o

octylFractal

07/21/2020, 3:42 AM
I'd say that's fine
r

Rechee Jozil

07/21/2020, 3:43 AM
@octylFractal Thanks. I thought so too at first but then I'm wondering if there's any issues I'm not seeing with it
g

gildor

07/21/2020, 3:48 AM
it’s fine, as can be fine any background task with side-effect
👍 1
View count: 6