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

    Tuan Kiet

    06/02/2019, 12:23 PM
    I wonder what is the use case of SupervisorJob, what is the case that you don’t care about your children job might throw an exception?
    t
    g
    • 3
    • 12
  • h

    haroldadmin

    06/03/2019, 6:21 AM
    Hello everyone! I'm trying to use a
    RendezvousChannel
    in the place of
    PublishSubject
    from RxJava in a project, but I need a way to access the current element in the channel without removing it. Something like a 'peek' operation on a
    LinkedBlockingQueue
    . Now a
    RendezvousChannel
    has a method called
    poll()
    which does give me the current element (or null) but it also removes it from the channel. How can I perform a peek operation on a channel then?
    l
    g
    • 3
    • 5
  • l

    louiscad

    06/03/2019, 9:50 AM
    Is there a
    collect
    variant for
    Flow
    that allows to access the previous value, or null for initial value?
    g
    e
    +2
    • 5
    • 15
  • v

    voddan

    06/03/2019, 12:39 PM
    @elizarov In the article you write that one should not use
    withContext
    inside a
    flow{}
    , basically. Can there be a realistic situation when such use is permitted? Maybe if
    emit
    is outside of
    withContext
    , or there are several `nested
    withContext
    that work in a way that protect the caller's context?
    e
    p
    • 3
    • 2
  • e

    Eric Martori

    06/03/2019, 3:25 PM
    Hello everybody. I was wondering if there is a way to
    emit
    values into a
    flow
    outside its building block. For example sending values when the user clicks a button or if this use-case would be better covered with something else instead of a
    Flow
    .
    s
    • 2
    • 9
  • j

    jw

    06/03/2019, 6:49 PM
    https://github.com/Kotlin/kotlinx.coroutines/pull/1236
    a
    e
    • 3
    • 3
  • t

    Tolriq

    06/04/2019, 7:11 AM
    @elizarov Anyway to have some feedback on https://github.com/Kotlin/kotlinx.coroutines/issues/1092 ? Just to be sure it's not forget due to the left label.
    e
    • 2
    • 2
  • r

    ribesg

    06/04/2019, 1:28 PM
    Is there any documentation somewhere on kotlinx.coroutines.io?
    • 1
    • 2
  • d

    Davide Giuseppe Farella

    06/04/2019, 8:17 PM
    Hello guys, any example about how to handle complex concurrency with `actor`s?
    t
    • 2
    • 11
  • m

    Melih Aksoy

    06/05/2019, 8:44 AM
    Hey all ! A quality check question - I have produce some data via
    flow
    in interactors, such as
    flow {
            emit(Result.State.Loading())
            emit(
                dataSourceFactory.getGrid(
                    params.path,
                    params.page,
                    params.displaySize
                )
            )
            emit(Result.State.Loaded())
    }
    An interactor is producing it’s own “state”, but I also want to support multiple interactors with single state. I came with an idea to merge them async in this way:
    fun CoroutineScope.merge(vararg results: Flow<SimpleResult<Any>>) = flow {
        emit(Result.State.Loading())
    
        val tasks = mutableListOf<Deferred<Unit>>()
    
        for (result in results) {
            tasks.add(
                async(<http://Dispatchers.IO|Dispatchers.IO>) {
                    result
                        .filterNot { it is Result.State }
                        .collect {
                            emit(it)
                        }
                }
            )
        }
    
        tasks.awaitAll()
        emit(Result.State.Loaded())
    }
    I’m wondering if this is a robust solution. This
    CoroutineScope
    is handled properly for closing etc., but what do you think ? Any suggestions to merge flows together while holding ability to ignore some emits ?
    e
    • 2
    • 5
  • t

    Tolriq

    06/05/2019, 9:10 AM
    How to properly initialize such kind of patterns? Currently depending on the state of the device and load, the repeat call can trigger creation of tons of threads even if there's no tasks yet. Generating a lot of unecessary load at init time.
    class XXX  : CoroutineScope {
    
    	override val coroutineContext = <http://Dispatchers.IO|Dispatchers.IO> + SupervisorJob()
    
    	internal val tasks = Channel<Task>(UNLIMITED)
    
        fun startWorkers() {
            repeat(150) {
                launch {
                    for (task in tasks) executeTask(task)
                }
            }
        }
    }
    z
    • 2
    • 14
  • p

    Paul Woitaschek

    06/05/2019, 11:33 AM
    import kotlinx.coroutines.*
    
    val job: Job = Job()
    val scope = CoroutineScope(Dispatchers.Default + job)
    
    fun throwsAsync(): Deferred<Unit> = scope.async {
      throw Exception()
    }
    
    fun loadData() = scope.launch {
      throwsAsync().await()
    }
    
    suspend fun main() {
      loadData().join()
      scope.launch { println("worked") }.join()
      joinAll()
      println("done")
    }
    Why doesn't this crash?
    m
    • 2
    • 2
  • p

    projectmoon

    06/05/2019, 1:29 PM
    i am trying to wrap my head around scopes, still. most examples online are simplistic uses of
    runBlocking
    ... use case here is that i need to, once a day run a bunch of operations as coroutines. currently this is a java scheduled executor, but i want to switch to coroutines for the actual running of the code.
    d
    g
    • 3
    • 21
  • v

    vishna

    06/05/2019, 3:33 PM
    example use case: saving a file to disk. Does using suspended function + continuation make sense here?
    inputStream_weaveTo_outputStream.kt
    s
    e
    g
    • 4
    • 10
  • p

    projectmoon

    06/05/2019, 5:03 PM
    is there any point to doing something like
    lauch { val result = async { doStuff() }.await() }
    , assuming
    doStuff()
    is a suspend fun? or would it make more sense to simply call
    doStuff()
    inside the launch block without
    async
    ?
    z
    j
    d
    • 4
    • 9
  • m

    mdapp

    06/05/2019, 5:51 PM
    So far I have
    runBlockingTest {
                whenever(model.loadData(false)).thenThrow(DeprecatedApiException())
    t
    • 2
    • 4
  • t

    Tolriq

    06/06/2019, 10:22 AM
    I'm having an hard time trying to figure out how merging of scope and context works and would appreciate some details 🙂
    class XXX  : CoroutineScope {
    
    	override val coroutineContext = <http://Dispatchers.IO|Dispatchers.IO> + SupervisorJob()
    
    	val aDispatcher =  ThreadPoolExecutor(...).asCoroutineDispatcher()
    
    	internal val tasks = Channel<Task>(UNLIMITED)
    
        fun startWorkers() {
            repeat(150) {
                launch(aDispatcher) {
    				val initialTask = try {
                        tasks.receive()
                    } catch (e: Exception) {
                        return@launch
                    }
                    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    					// Correctly run on <http://Dispatchers.IO|Dispatchers.IO>
    				}
    			}
            }
        }
    }
    class XXX  : CoroutineScope {
    
    	override val coroutineContext = <http://Dispatchers.IO|Dispatchers.IO> + SupervisorJob()
    
    	val aDispatcher =  ThreadPoolExecutor(...).asCoroutineDispatcher()
    
    	internal val tasks = Channel<Task>(UNLIMITED)
    
        fun startWorkers() {
            repeat(150) {
                launch(aDispatcher) {
    				val initialTask = try {
                        tasks.receive()
                    } catch (e: Exception) {
                        return@launch
                    }
                    withContext(coroutineContext) {
    					// Incorrectly runs on aDispatcher instead of <http://Dispatchers.IO|Dispatchers.IO> that is used for coroutineContext
    				}
    			}
            }
        }
    }
    b
    • 2
    • 2
  • a

    aaverin

    06/06/2019, 11:07 AM
    I am doing Coroutines-Rx2 interop. According to https://github.com/Kotlin/kotlinx.coroutines/blob/master/reactive/kotlinx-coroutines-rx2/src/RxConvert.kt
    @ExperimentalCoroutinesApi
    public fun <T : Any> Deferred<T>.asSingle(context: CoroutineContext): Single<T> = GlobalScope.rxSingle(context) {
        this@asSingle.await()
    }
    calling
    myDeferred.asSingle(coroutineContext)
    will immediately call
    await()
    on the deferred, which effectively starts coroutine execution. Shouldn’t this only happen when Single will be subscribed on?
    b
    s
    z
    • 4
    • 33
  • l

    louiscad

    06/06/2019, 2:03 PM
    Do you think passing a
    CompletableDeferred
    down a
    Flow
    or a
    Channel
    (exposed as a
    ReceiveChannel
    ) is a good idea? The use case is to allow to observe a state (a sealed class instance), and allow an action depending on that state.
    u
    s
    z
    • 4
    • 4
  • d

    Dico

    06/06/2019, 4:24 PM
    Is there a particular reason why
    AtomicInt
    from kotlinx:atomicfu doesn't declare these:
    operator fun plusAssign
    (+=)
    operator fun minusAssign
    (-=)
    operator fun inc
    (++)
    operator fun dec
    (--) In Java, these couldn't be atomic, but since you can implement them yourself, they would be. For
    inc
    and
    dec
    I guess it might be because they would have to return AtomicInt, instead of Int. Asking here because I didn't see an atomicfu channel.
    r
    • 2
    • 7
  • v

    Vsevolod Tolstopyatov [JB]

    06/06/2019, 9:14 PM
    📣 📣 📣
    kotlinx.coroutines
    version 1.3.0-M1 is here! A lot of changes in Flow: * Core
    Flow
    interfaces and operators are graduated from preview status to experimental 😒uspend: * Serious performance improvements of Flow * More accurate context preservation invariant that should prevent most of the concurrency and contract violation bugs *
    Flow
    interface cannot be implemented directly, only via
    AbstractFlow
    to preserve Flow’s invariant * Separate
    buffer
    operator composable with buffered operator (
    flowOn
    ,
    flowChannel
    etc.). No more
    bufferSize
    constant in operators! * New operators and a lot more! General changes: * Scalable state-of-the-art
    Semaphore
    implementation * Channels API improved: performance, experimental API and consistent exception handling *
    withContext
    checks cancellation status on exit to make reasoning about sequential concurrent code easier * JS dispatcher performance * Various API and performance improvements and bug fixes Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.3.0-M1
    👌 8
    😍 6
    👏 7
    😎 6
    👍 5
    🎉 29
    😒uspend: 19
    🔥 27
    :kotlin: 15
    b
    l
    +2
    • 5
    • 6
  • l

    louiscad

    06/07/2019, 9:04 AM
    It seems replacement for
    flowViaChannel(Channel.CONFLATED) { … }
    is
    channelFlow<T> { … }.buffer(Channel.CONFLATED)
    . Isn't that less efficient as values pass through 2 operators?
    e
    r
    • 3
    • 14
  • r

    ribesg

    06/07/2019, 9:11 AM
    Is
    kotlinx-coroutines-test
    planned for multiplatform?
    l
    v
    j
    • 4
    • 3
  • m

    Mark

    06/07/2019, 10:24 AM
    What is the equivalent of SingletonHolder when using coroutines: https://medium.com/@BladeCoder/kotlin-singletons-with-argument-194ef06edd9e
    open class SingletonHolder<out T: Any, in A>(creator: (A) -> T) {
        private var creator: ((A) -> T)? = creator
        @Volatile private var instance: T? = null
    
        fun getInstance(arg: A): T {
            val i = instance
            if (i != null) {
                return i
            }
    
            return synchronized(this) {
                val i2 = instance
                if (i2 != null) {
                    i2
                } else {
                    val created = creator!!(arg)
                    instance = created
                    creator = null
                    created
                }
            }
        }
    }
    g
    • 2
    • 1
  • g

    gildor

    06/07/2019, 10:31 AM
    Never use this anti-pattern is the solution
    :yes: 2
    m
    w
    +2
    • 5
    • 45
  • t

    Thomas

    06/07/2019, 12:01 PM
    Could anyone explain to me why this code throws an exception (on Android)? The
    collect
    and
    cancel
    functions are both called on the main thread. I tried this with both version 1.2.1 and 1.3.0-M1
    var cancelled = false
    val job = GlobalScope.launch(Dispatchers.Main) {
        val flow = flow {
            while (true) {
                emit(Unit)
            }
        }
        flow.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
            .collect {
                if (cancelled) { // main thread
                    throw IllegalStateException()
                }
            }
    }
    
    GlobalScope.launch(Dispatchers.Main) {
        delay(1000)
        job.cancel() // main thread
        cancelled = true
    }
    a
    • 2
    • 24
  • t

    tseisel

    06/07/2019, 12:35 PM
    Does something like a hot
    Flow
    make sense, or is
    Flow
    dedicated to only cold asynchronous streams while `Channel`s are the best choice for hot streams ?
    g
    a
    • 3
    • 7
  • e

    Eric Martori

    06/07/2019, 3:00 PM
    I am trying to create an InvocableFlow, the idea is being able to send values without outside the declaration site of the flow while still exposing a flow Api, would this implementation actually work? Is there any flow in my approach? :
    internal class InvocableFlow<T>(private val scope: CoroutineScope) {
        val flow = flow {
            for (value in channel.openSubscription()) {
                emit(value)
            }
        }
    
        private val channel = BroadcastChannel<T>(BUFFERED)
    
        fun invoke(data: T) {
            scope.launch {
                channel.send(data)
            }
        }
    }
    g
    z
    • 3
    • 13
  • a

    Allan Wang

    06/07/2019, 5:58 PM
    Is there a reason why there aren’t delay functions for channels, and only for flows? https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/flow/operators/Delay.kt Is it just that it isn’t as efficient to do so with hot streams?
    e
    • 2
    • 1
  • b

    blakelee

    06/07/2019, 7:58 PM
    Is there a CompletableDeffered with a reset? Such as, once I get my result, I can choose to reset it so that if I want to call await() again it has to wait for a new value. Or perhaps I’m just looking for a different class
    b
    l
    • 3
    • 2
Powered by Linen
Title
b

blakelee

06/07/2019, 7:58 PM
Is there a CompletableDeffered with a reset? Such as, once I get my result, I can choose to reset it so that if I want to call await() again it has to wait for a new value. Or perhaps I’m just looking for a different class
b

bdawg.io

06/08/2019, 4:17 AM
Deferred
is isolated from how the value is being obtained, so it's not resettable unfortunately. The Flow/generic suspend function should fill your needs though
l

louiscad

06/08/2019, 6:23 AM
A Channel with a capacity of 1, 0 or conflated should fit your needs
View count: 3