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

    Marko Mitic

    11/04/2019, 1:44 PM
    Are there any coroutines-friendly error handling functions? For example, some
    runCatching
    that doesn't catch
    CancellationException
    ? Would be nice to have some standardized solution (and IDE warnings on catching the
    CancellationException
    in coroutines)
    ➕ 2
    l
    g
    18 replies · 3 participants
  • v

    Vincent Williams

    11/04/2019, 5:13 PM
    This may be a stupid question, but does anyone know why coroutines in kotlin were designed the way they are? It seems like concurrency in other languages is much simpler with easier to understand syntax (im thinking async await). To me it seems coroutines in kotlin have a higher learning curve than what I have seen in other languages and im wondering if this was something done on purpose or if it will get better as time goes on.
    z
    m
    +4
    12 replies · 7 participants
  • l

    Luis Munoz

    11/04/2019, 8:04 PM
    I have the code above to wrap my tests in so they timeout. But some how test is not timing out, they keep running for ever. Anyone know why this wrapper may fail?
    Untitled
    o
    7 replies · 2 participants
  • j

    John

    11/04/2019, 9:48 PM
    Is a scope unable to be launched twice? I.e. after finishing or being cancelled?
    o
    s
    2 replies · 3 participants
  • v

    vineethraj49

    11/05/2019, 12:57 AM
    do
    test1()
    and
    test2()
    end up doing the same? (my guess: yes) test1:
    async(<http://Dispatchers.IO|Dispatchers.IO>) { [...] }
    test2:
    suspend fun logic() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { [...] }; async { logic() }
    if so, which is more idiomatic?
    Untitled
    s
    3 replies · 2 participants
  • v

    vineethraj49

    11/05/2019, 1:05 AM
    Can I add my custom element to
    coroutineContext
    like
    coroutineContext[Job]
    that propagates to all children; if yes, are there any pointers for doing the same?
    o
    1 reply · 2 participants
  • k

    Kroppeb

    11/05/2019, 3:09 AM
    The follow code will never end, and if forcefully stopped the dump lists no coroutines. I have a workaround but I was wondering if this is a bug or just how it's supposed to be? It feels counterintuitive.
    runBlocking {
    	fun tt(s: CoroutineScope) = s.launch(start = CoroutineStart.LAZY) { }
    	val s = this
    	tt(s)
    }
    o
    s
    +1
    6 replies · 4 participants
  • s

    Slackbot

    11/05/2019, 8:13 AM
    This message was deleted.
    a
    m
    2 replies · 3 participants
  • f

    Frank Feng

    11/05/2019, 9:22 AM
    There is no event loop. Use runBlocking{...} to start one
    I run the kotlin native lib on iOS, it throw this error.
    v
    l
    5 replies · 3 participants
  • k

    Klara Erlebachova

    11/05/2019, 5:09 PM
    Hi, is there any way to use
    runBlocking
    with K/N? I used it in my MPP project for synchronous API and works fine on Android but on iOS it never returns. Even very simple example like this:
    val result = runBlocking(MainDispatcher) {
                return@runBlocking "yes"
            }
    l
    4 replies · 2 participants
  • k

    kd

    11/05/2019, 7:00 PM
    I have an exceptionHandler passed to the the scope.launch and based on a certain exception I want to stop the coroutine and then restart it. Is this the correct way to achieve it?
    Untitled
    o
    5 replies · 2 participants
  • u

    ubu

    11/05/2019, 8:59 PM
    I have a
    ViewModel
    observing flow of user accounts:
    Account1
    ,
    Account2
    , `Account3`… Then for each of these accounts I need to load an image (represented as
    blob
    ) from some remote source. This loading may take a while, that’s why I show user accounts first without their picturse, then update
    UI
    with the same model having now picture data. First of all, it feels a bit weird to load images inside
    onEach
    operator. Or not? And then, maybe it’s not a good idea at all to load picture data inside a
    ViewModel
    . What do you think?
    class SelectAccountViewModel(
        private val startLoadingAccounts: StartLoadingAccounts,
        private val observeAccounts: ObserveAccounts,
        private val loadImage: LoadImage
    ) : ViewModel(), SupportNavigation<Event<AppNavigation.Command>> {
    
        val state by lazy { MutableLiveData<List<ChooseProfileView>>() }
    
        private val accountChannel = Channel<Account>()
        private val imageChannel = Channel<ImageBlob>()
    
        init {
            startObservingAccounts()
            //startLoadingAccount()
    
            viewModelScope.launch {
    
                val accumulatedAccounts = accountChannel
                    .consumeAsFlow()
                    .onEach { account -> loadImage(account) }
                    .scan(emptyList<Account>()) { list, value -> list + value }
    
                val accumulatedImages = imageChannel
                    .consumeAsFlow()
                    .scan(emptyList<ImageBlob>()) { list, value -> list + value }
    
                accumulatedAccounts.combine(accumulatedImages) { accounts, images ->
                    accounts.associateWith { account ->
                        images.firstOrNull { it.id == account.id }
                    }
                }.collect { result ->
                    state.postValue(
                        result.map { (account, image) ->
                            ChooseProfileView.ProfileView(
                                id = account.id,
                                name = account.name,
                                image = image?.blob
                            )
                        }
                    )
                }
            }
    
        }
    }
    And then, these other questions arise: is it okay to use channels as shown above? Could one be more concise with coroutines?
    z
    2 replies · 2 participants
  • z

    zak.taccardi

    11/05/2019, 10:10 PM
    Is there a general timeline for when the Kotlin Coroutines team is looking to release
    1.4.0-RC
    ?
    🎉 1
    b
    m
    +3
    11 replies · 6 participants
  • v

    vineethraj49

    11/06/2019, 8:42 AM
    is this (spawning
    async(Dispatchers.Default)
    on
    runBlocking
    ) ok, or will this blow up in my face?
    Untitled
    o
    b
    9 replies · 3 participants
  • d

    Derek Berner

    11/06/2019, 8:25 PM
    Recursive as in, the consumer of the flow can send more messages to it
    o
    b
    10 replies · 3 participants
  • j

    Jason

    11/07/2019, 3:32 AM
    Hi guys! How to you polling with
    flow
    . I just want to looping forever by using Flow of coroutine. Actually I dont like while(true). Any support method ?
    s
    e
    3 replies · 3 participants
  • d

    dariuszbacinski

    11/07/2019, 8:36 AM
    @Test
        fun coroutineTest() {
            runBlocking {
                flowOf("any").map {
                    val result = ioFunction() //crash java.lang.ClassCastException: kotlin.coroutines.intrinsics.CoroutineSingletons cannot be cast to java.util.Map
                    result
                }.collect { result ->
                    Log.v("$result")
                }
            }
        }
    
        suspend fun ioFunction(): Map<Long, Int> = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            mapOf(1L to 4)
        }
    how can is use suspend function in when mapping Flow? above code crashes, but it works when I remove suspend function and use normal blocking function
    ✔️ 1
    o
    8 replies · 2 participants
  • p

    Paul Woitaschek

    11/07/2019, 9:20 AM
    I need help 🙂 I have an issue with undeclared throwables in retrofit when switching to Dispatchers.Main.Immediate. https://github.com/square/retrofit/issues/3128#issuecomment-550989230 https://jakewharton.com/exceptions-and-proxies-and-coroutines-oh-my/ What's so special with
    Dispatchers.Main.immediate
    that causes this behavior?
    o
    l
    5 replies · 3 participants
  • g

    ghedeon

    11/07/2019, 1:11 PM
    When running with
    Dispatchers.Main.immediate
    , what is the the best way to execute a portion immediately and
    launchAndForget
    the rest? Ex:
    suspended fun foo(){
        operationA()  // <--- don't wait for it, it's on IO
        operationB() // <--- post on Main immediately
    }
    It already works if I swap the order, like
    operationB() // <--- post on Main immediately
        operationA()  // <--- don't wait for it, it's on IO
    But I'm looking for a way that doesn't depend on the order of operations.
    l
    8 replies · 2 participants
  • e

    elaborate tissue

    11/07/2019, 2:28 PM
    Need help with what dispatchers i'm supposed to use.. So far I tried:
    runBlocking {
                launch (Dispatchers.Unconfined) {
                    // check every x seconds if file exists, if it does then kill app (and all other coroutines)
                }
                launch (<http://Dispatchers.IO|Dispatchers.IO>) {
                    // every x seconds send metrics to server
                }
                for (i in 1..Runtime.getRuntime().availableProcessors()) {
                    launch (Dispatchers.Default) {
                        // use remaining cpu/mem resources to process batch items
                    }
                }
            }
    running this means that when all available processors are doing work, the jobs which are supposed to run every x seconds never run, how am I supposed to get them to run regularly regardless of if available processors are performing the batch work?
    w
    5 replies · 2 participants
  • j

    James

    11/07/2019, 5:17 PM
    Couldn't this part of this article (image below) https://proandroiddev.com/kotlin-coroutines-channels-csp-android-db441400965f be done with a semaphore much easier? I get that channels can help when your application gets bigger, but i'm wondering if channels are a bit much for this problem. With a semaphore implementation the methods would still suspend until one of the workers could be freed up
    c
    o
    6 replies · 3 participants
  • j

    jeff

    11/07/2019, 6:17 PM
    Hi all -- I have a Flow<> and for each item, I want to make a potentially-long-running network call. I would like these calls to happen in parallel. I can achieve that by doing
    myFlow
    .flatMapMerge { item ->
        flow { emit(suspendingFunctionThatMakesNetworkCall(item)) }
    }
    HOWEVER, Flow's flatMapMerge() has the following comment
    Note that even though this operator looks very familiar, we discourage its usage in a regular application-specific flows.
    Most likely, suspending operation in [map] operator will be sufficient and linear transformations are much easier to reason about.
    I can't figure out how to do this with just a suspend map. Help?
    o
    3 replies · 2 participants
  • d

    David Glasser

    11/07/2019, 7:59 PM
    Hmm. So I was under the impression that the "normal" way to make a program that uses coroutine was
    fun main() = runBlocking {
    We just discovered that this leads to coroutines being run single-threaded by default, not in Dispatchers.Default. This is a big surprise! Is the normal pattern supposed to be
    fun main() = runBlocking(Dispatchers.Default) {
    ?
    o
    m
    +1
    11 replies · 4 participants
  • v

    Vsevolod Ganin

    11/07/2019, 8:17 PM
    Hi! Is there any known cases when
    GlobalScope.launch(Dispatchers.Unconfined)
    will actually dispatch? I stumbled upon some case when
    GlobalScope.launch(start = CoroutineStart.UNDISPATCHED, context = Dispatchers.Unconfined)
    !=
    GlobalScope.launch(Dispatchers.Unconfined)
    but I can’t quite figure what’s causing it
    o
    10 replies · 2 participants
  • s

    Slackbot

    11/07/2019, 9:23 PM
    This message was deleted.
    👍 1
    g
    1 reply · 2 participants
  • j

    Jérôme Gully

    11/07/2019, 10:45 PM
    Hi. I'm relatively new to Coroutines. Is it okey to use
    GlobalScope.launch { }
    to run an infinite while to draw on canvas (Android SurfaceView) or it is a better solution ?
    Sans titre
    z
    22 replies · 2 participants
  • k

    Kulwinder Singh

    11/08/2019, 8:12 AM
    I have
    LiveData<List<User>>
    loaded from firestore now i want to load `Appointment`s for each user from firestore, in end i want to create something like this
    Map<User,Appointment>
    . which
    flow
    operator can helps me in this situation, or flow is not best suited for this?
    z
    1 reply · 2 participants
  • t

    tseisel

    11/08/2019, 9:36 AM
    How would you do parallel processing with
    Flow
    ? 1. Map T to a
    Deferred<R>
    , then await each ? 2. Use plain coroutines with channels ?
    d
    r
    4 replies · 3 participants
  • v

    vineethraj49

    11/08/2019, 10:13 AM
    does
    launch(customDispatcher)
    block if customDispatcher can’t find a free thread?
    🇳🇴 1
    d
    2 replies · 2 participants
  • j

    Jakub Walusiak

    11/08/2019, 1:21 PM
    Untitled.kt
    k
    9 replies · 2 participants
Powered by Linen
Title
j

Jakub Walusiak

11/08/2019, 1:21 PM
Untitled.kt
k

Kroppeb

11/08/2019, 1:46 PM
If you only return 1 item I'd use a
CompletableDeferred
instead of a channel.
j

Jakub Walusiak

11/08/2019, 2:04 PM
My goal is to create a channel-based solution, without handler and consumer knowing each other
I don't know how could I archieve this with CompletableDeferred
k

Kroppeb

11/08/2019, 2:47 PM
This might be unethical code (I don't really know what is considered bad practice yet) but would this do what you want?
Untitled
j

Jakub Walusiak

11/08/2019, 2:47 PM
probably, though I think I found a way
Untitled
k

Kroppeb

11/08/2019, 2:50 PM
job.join() shouldn't be needed I think
j

Jakub Walusiak

11/08/2019, 2:52 PM
hmm, you're right
coroutineScope should wait for all its children
View count: 2