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

    rkeazor

    10/01/2019, 12:11 PM
    oh wait its marked as obsolete, so im guessing it will stay until there is a replacement for it. Than be deprecated
    a
    • 2
    • 1
  • d

    Dennis Schröder

    10/01/2019, 9:52 PM
    I recently read something that I interpreted as being bad.
    suspend fun someFunctionCreatesAFlow(context: Dispatchers.Default): Flow<String> = withContext(context) {
     flow {
        emit(somethingAsAString)
       } 
    }
    I guess it is because Flows kinda manage their own context with
    flow::flowOn()
    . Can anybody confirm this?
    d
    o
    +3
    • 6
    • 19
  • r

    Ran Magen

    10/01/2019, 10:42 PM
    Hey, quick question, I was wondering about the cost of creating a
    coroutineScope
    that ends up doing nothing. For example should I bother writing:
    if (collection.isNotEmpty()) {
      coroutineScope {
        collection.forEach { item -> launch { doSomeComplexSuspendingWork(item) } }
      }
    }
    Or does it not really matter much and this would be just as efficient (and cleaner to read)
    coroutineScope {
      collection.forEach { item -> launch { doSomeComplexSuspendingWork(item) } }
    }
    o
    l
    • 3
    • 3
  • r

    Robert Menke

    10/02/2019, 12:54 AM
    Are there any articles out there that compare coroutines to Apple’s Grand Central Dispatch (GCD)? Curious to read up on comparisons between the two.
    b
    • 2
    • 3
  • y

    ylemoigne

    10/02/2019, 10:11 AM
    When there is a jdk IO blocking call inside coroutine and we're not in IO dispatcher context, intellij show a warning. Is there a way to tag a custom method as blocking IO to get this warning ?
    ➕ 1
    l
    k
    • 3
    • 2
  • y

    Yoav Gross

    10/02/2019, 2:10 PM
    I’m trying to subscribe to
    rxjava
    events and consume them as
    flow
    , it seems i’m not subscribing correctly with flow or missing to correlating action to rx
    subscribe
    This is the
    flow
    usage, i’m expecting to collect each change to the data from the
    flowable
    i’m listening to:
    runBlocking {
                getSubtitleFromProjectDataManager()
            }
    
    private suspend fun getSubtitleFromProjectDataManager() {
            scope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    
                val flow = projectDataManager.getProjectNameFlowable().asFlow()
                flow.collect {
                    subtitle = it
    
                }
                launch(Dispatchers.Main) {
                    view?.rebindToolbar()
                }
            }
        }
    This is the rxjava code I’m trying to listen to. Indeed the event isn’t firing again when the data is changed, so I suspect as said before there is a subscription issue:
    public Flowable<String> getProjectNameFlowable() {
            return RxJavaInterop.toV2Flowable(
                    getSelectedProject()
                            .switchMap(projectEntity -> {
                                        Timber.e("fire projectEntity " + projectEntity.title());
                                        return Observable.just(projectEntity.title());
                                    }
                            ));
        }
    👋 1
    l
    r
    • 3
    • 11
  • b

    bnn

    10/02/2019, 10:19 PM
    Hi there. When I want to create some immediately returning method in a class, I usually write class in following manner.
    class Foo(ctx: CoroutineContext) {
        val scope = CoroutineScope(ctx)
    
        fun launchSome() = scope.launch { ... }
    }
    Are there better ways or conventions to do that? I wonder some possibilities such as ... - To implement CoroutineScope (
    class Foo(ctx: CoroutineContext = ... : CoroutineScope { ... }
    ) - To define method as CoroutineScope extension function (
    fun CoroutineScope.launchSome() = launch(ctx) {...}
    ) Thanks.
    g
    l
    • 3
    • 9
  • b

    Brad Murray

    10/02/2019, 11:31 PM
    Underlying architecture is Ktor, using the CIO Httpclient. The client errors are caught and logged nicely, so I'm not aware of where any uncaught exceptions should be triggering cancellation of the Jobs
    👀 1
    e
    • 2
    • 1
  • s

    spierce7

    10/03/2019, 3:27 AM
    I’m getting an error when trying to collect a flow. This seems odd:
    GlobalScope.launch {
        flow.collect {
        }
    }
    I’ve found other examples where a lambda works as a flow collector.
    p
    l
    +4
    • 7
    • 50
  • b

    bitkid

    10/03/2019, 1:51 PM
    so i watched this video

    https://www.youtube.com/watch?v=a3agLJQ6vt8▾

    and i tried to recreate what he was doing with downloading with an uploader. https://gist.github.com/bitkid/c66d198c2930bd4c5dbc753cf96b4c2f . i have uploadWorkers (inputchannel with files, output channel with uploadResponse), an uploadResultHandler which listenes to the uploadResponseChannel and a "main" method which combines the workers with handler. the problem i have now .. how do i write a main method for that. so how does the resulthandler know that he is done listening to uploadresults? i can't close the response channel in the worker .. basically i am confused 🙂
    r
    b
    • 3
    • 22
  • t

    taer

    10/03/2019, 10:01 PM
    Got a flow question for y'all.. It's about ....
    Exception in thread "main" java.lang.IllegalStateException: Flow invariant is violated:
    		Emission from another coroutine is detected.
    		Child of StandaloneCoroutine{Active}@2b552920, expected child of BlockingCoroutine{Completing}@2758fe70.
    		FlowCollector is not thread-safe and concurrent emissions are prohibited.
    		To mitigate this restriction please use 'channelFlow' builder instead of 'flow'
    z
    p
    b
    • 4
    • 14
  • d

    dharrigan

    10/04/2019, 8:36 AM
    fun updateDetails() = GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        // loop forever
        updateDetailsAsync()
        // wait until updateDetailsAsync is done
    }
    
    fun CoroutineScope.updateDetailsAsync() {
        does an REST API lookup
        writes into a database
    }
    s
    d
    • 3
    • 16
  • d

    Dominaezzz

    10/04/2019, 10:38 AM
    When should I use
    val scope = SupervisorScope()
    over
    val scope = CoroutineScope(CoroutineExceptionHandler { ctx, e -> })
    ?
    s
    • 2
    • 4
  • w

    wakingrufus

    10/04/2019, 2:31 PM
    What is the best current workaround for this: https://github.com/Kotlin/kotlinx.coroutines/issues/1147 I would like to have a flow that launches many async processes in parallel and collects the results into the flow.
    d
    • 2
    • 7
  • t

    tseisel

    10/04/2019, 2:59 PM
    For testing purposes, I need a flow that never completes (similar to
    Flowable.never()
    ) Is something like this correct ?
    object NeverFlow : Flow<Nothing> {
        override suspend fun collect(collector: FlowCollector<Nothing>) {
            delay(Long.MAX_VALUE)
        }
    }
    s
    e
    • 3
    • 4
  • b

    bnn

    10/05/2019, 2:54 AM
    Does anybody know good ways to avoid following issue.
    fun main() = runBlocking {
        val f = channelFlow {
            launch {
                while (true) {
                    offer(1)
                    delay(500)
                }
            }
    
            awaitClose {
                println("f1 closed")
            }
        }
    
        val b = f.broadcastIn(this).apply {
            /**
             * If uncomment the following code, Exception below will be raised.
             *
             * java.lang.IllegalStateException: Another handler was already registered 
             *
             * You cannot onClose callback twice for same SendChannel.
             *
             * There is already onClose callback in this code: awaitClose callback inside channelFlow builder
             *
             */
            // invokeOnClose { println("b1 closed") }
        }
    
        launch {
            b.openSubscription().consumeAsFlow().take(5).collect {
                println(it)
            }
            b.cancel()
        }.join()
    }
    As I commented in the inline comment,
    invokeOnClose
    on the BroadcastChannel which is issued by broadcatIn terminal function on the Flow instance created by channelFlow builder would throws
    java.lang.IllegalStateException Another handler was already registered
    . Though It is possible to understand soon with this short sample code, it's sometimes hard to know whether the Flow instance is created by channelFlow when you
    broadcastIn
    on it.
    d
    • 2
    • 2
  • u

    ursus

    10/07/2019, 12:09 AM
    Hi, If I have a custom scope for my component, but also want granular
    fun cancel(id: Id)
    , i.e. I need my jobs keyed for that. Should I have some separate map for this? Feels like scope functionality, but in order for that I'd need the scope to be backed by a map, or iterate its jobs?
    b
    • 2
    • 4
  • y

    ylemoigne

    10/07/2019, 6:59 AM
    I must have misunderstood something. Can anyone explain to me why this is blocking and the
    println("Start receiving...
    is not executed ? (or point me to the revelant part of documentation)
    Untitled
    o
    • 2
    • 4
  • n

    neworldlt

    10/07/2019, 10:04 AM
    I am wondering, why cached exception of
    await()
    still cancels parent job? Let assume this example: https://pl.kotl.in/DlU1vaR2T. If you comment out
    await()
    part, launch's job will stay active
    l
    • 2
    • 2
  • u

    ubu

    10/07/2019, 2:03 PM
    Hi there! I have trouble integrating synchronous code with coroutines, in order to get that broadcasting feature I was able to implement using `RxJava`:
    class Handler : MessageHandler {
    
        private val channel = Channel<Message>(1)
    
        override fun handle(message : Message) {
            // TODO send event.
        }
    
        fun send(event : Message) {
            
        }
    
    /*
        fun observe() : Channel<Message>
        fun observe() : Flow<Message>
    */
    }
    When having `RxJava`’s
    subjects
    , I could call
    onNext()
    , let observers consume it by exposing some
    Observable
    . Is there a way to do the same with
    Coroutines
    ? I need to expose some methods that allow to observe stream of events received in
    handle(message : Message)
    method. Thanks a lot in advance!
    z
    p
    • 3
    • 16
  • j

    Joe

    10/07/2019, 3:46 PM
    is there a practical difference between these two ways of converting a
    java.util.Stream
    to a
    Flow
    ? would the first generally be the preferred way (or is there another, more idiomatic way?):
    result.iterator().asFlow().onCompletion { result.close() }
    vs
    flow {
        result.use {
            for (edge in it) {
                emit(edge)
            }
        }
    }
    g
    e
    • 3
    • 5
  • z

    zak.taccardi

    10/07/2019, 6:10 PM
    should a function or property be used to represent a ViewModel’s stream of states? vote
    1
    for property and
    2
    for function
    ViewModel
    1️⃣ 10
    z
    • 2
    • 3
  • g

    groostav

    10/07/2019, 9:39 PM
    is there a factory to fan-in two
    Flow<T>
    instances into a single
    Flow<T>
    d
    o
    +2
    • 5
    • 11
  • e

    eygraber

    10/08/2019, 1:24 AM
    Is there any way to retrieve the dispatcher from a coroutine context?
    a
    • 2
    • 6
  • j

    Joe

    10/08/2019, 4:52 AM
    We have code similar to this:
    val job = launch {
        val flow = slowBlockingCallThatReturnsIterator().asFlow()
        flow.collect { 
            yield() // allows for cancel() to work
            channel.send(it) 
        }
    }
    If we call
    job.cancel()
    during the slowBlockingCall (or while the flow is collecting) without the
    yield()
    call, all entries in the iterator still get sent to the channel. If we add back the yield call, then the collection aborts as we initially expected to happen without the yield(). Since channel.send is a suspend function, shouldn't calling it check the coroutine active state?
    o
    • 2
    • 3
  • d

    darkmoon_uk

    10/08/2019, 6:45 AM
    If I have multiple child Jobs in a coroutine scope and one fails, I understand this cancels all the other children. My question is: Is
    GlobalScope
    any different in this regard? Will a failed Job in
    GlobalScope
    cancel everything in
    GlobalScope
    ?
    o
    • 2
    • 2
  • d

    darkmoon_uk

    10/08/2019, 6:48 AM
    ...and if this is the case, is use of
    supervisorScope
    mandatory wherever a coroutine might fail, to avoid the entire concurrency tree being taken down?
    v
    • 2
    • 1
  • p

    Paul Woitaschek

    10/08/2019, 8:15 AM
    I need a
    PublishSubject
    alternative as flow. The closest representation I found is a
    Channel(RENDEZVOUS)
    . However the
    consumeAsFlow
    function states:
    If the flow consumer fails with an exception, channel is cancelled.
    I don't want that. Is there an alternative for that?
    l
    l
    e
    • 4
    • 12
  • k

    Kulwinder Singh

    10/08/2019, 11:16 AM
    i'm using this
    callbackFlow
    to listen updates of Firestore Collection using below extension function
    @ExperimentalCoroutinesApi
    fun Query.getQuerySnapshotFlow(): Flow<QuerySnapshot?> = callbackFlow {
        val listenerRegistration = addSnapshotListener { querySnapshot, e ->
            if (e != null) {
                cancel(message = "", cause = e)
                return@addSnapshotListener
            }
            offer(querySnapshot)
        }
        awaitClose {
            listenerRegistration.remove()
        }
    }
    
    @ExperimentalCoroutinesApi
    fun <T> Query.getDataFlow(mapper: (QuerySnapshot?) -> T): Flow<T> {
        return getQuerySnapshotFlow().map { mapper(it) }
    }
    and i'm using above extension functions like below inside my ViewModel, but how can i cancel previous
    Flow
    , which is started in
    else
    case below, because when
    switchMap
    is called again then it will keep listening old Collection and will start new one. how can i fix this?
    val myAppointments = _appointmentDate.switchMap { date ->
    	//HERE I WANT TO CANCEL PREVIOUS FLOW STARTED IN ELSE CASE BELOW
    	liveData {
    		if (date == null)
    			emit(AppointmentState.NoAppointment)
    		else {
    			myCollection.whereEqualTo(Appointment.DATE, date)
    					.getDataFlow { it!!.toObjects<List<Appointment>>() }
    					.collect { emit(AppointmentState.Loaded(it)) }
    		}
    	}
    }
    m
    • 2
    • 7
  • k

    kupris

    10/08/2019, 3:01 PM
    Untitled
    e
    • 2
    • 2
Powered by Linen
Title
k

kupris

10/08/2019, 3:01 PM
Untitled
e

Evan R.

10/08/2019, 3:03 PM
Is an exception being thrown that the empty CEH is ignoring?
k

kupris

10/08/2019, 3:09 PM
Hi Evan, thanks for your time, I tried in debug, I don't receive any exception in the handler.
View count: 5