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

    rook

    04/29/2019, 7:49 PM
    What causes the IDE to recommend using
    withContext(Dispatchers.Default)
    over
    async
    ? Is
    withContext
    more optimal, somehow?
    s
    l
    g
    • 4
    • 5
  • s

    serebit

    04/30/2019, 3:46 PM
    kotlinx.coroutines doesn’t seem to have a version out that’s binary compatible with the latest kotlin/native compiler. When can we expect to see such a release?
    e
    • 2
    • 2
  • a

    andreworobator

    05/01/2019, 12:45 AM
    According to a recent article on /r/AndroidDev by Sean McQuillan, all suspending functions should be main safe and use
    withContext(...)
    depending on what they’re doing. If
    withContext(<http://Dispatchers.IO|Dispatchers.IO>)
    always runs on a background thread, how can we ensure single threading for testing purposes? Even
    runBlocking()
    doesn’t affect this.
    p
    s
    g
    • 4
    • 6
  • a

    ansman

    05/01/2019, 4:49 PM
    What’s the best way to cleanup things that you create in a coroutine? I’m especially worried about removing created resources when being cancelled.
    myScope.launch {
        // If the job is canceled before createResourceSync() returns the resource is lost in transit
        val resource = withContext(Dispatchers.default) { createResourceSync() }
        try {
        } finally {
          resource.delete()
        }
    }
    d
    • 2
    • 38
  • b

    basher

    05/02/2019, 12:30 AM
    If you create a class that implements CoroutineScope and keeps a local property to a
    Job
    , is the job cancelled if that object and the job are collected?
    s
    e
    k
    • 4
    • 7
  • p

    Paul Woitaschek

    05/02/2019, 8:36 AM
    Is there sth
    concatWith
    for Flow?
    o
    d
    • 3
    • 4
  • s

    Schadenfreude

    05/02/2019, 2:54 PM
    Hey guys, I’m trying to await a result of a callback from the Amazon LWA sdk but it’s a bit advanced and confusing for me. This is their method:
    AuthorizationManager.getToken(context, SCOPES, tokenListener)
    I want to wait for it to get the result in the listener and then continue on with my code but I can’t figure out if it’s at all possible.
    s
    l
    +2
    • 5
    • 15
  • k

    kevin.cianfarini

    05/02/2019, 10:37 PM
    Can anyone explain to me the benefit of a
    CoroutineScope
    being provided in AndroidX LifeCycle as an extension
    viewModelScope
    versus just having viewmodel implement
    CorutineScope
    ?
    l
    g
    • 3
    • 8
  • m

    Mark

    05/03/2019, 3:45 AM
    How to convert
    fun myFun(): LiveData<MyClass>
    to a suspend function that returns as soon as the LiveData value is set (i.e. the first time since LiveData created)? Note - the actual scenario is Room where I sometimes want LiveData<List> and othertimes just want the List of results, but don’t want to specify the SQL annotation twice. The best I have so far is:
    suspend fun mySuspendFun() = suspendCoroutine<List<MyClass>> { cont ->
            val live = myFun()
            live.observeForever(object: Observer<List<MyClass>> {
                override fun onChanged(it: List<MyClass>) {
                    live.removeObserver(this)
                    cont.resume(it)
                }
            })
        }
    • 1
    • 2
  • k

    kluck

    05/03/2019, 7:09 AM
    Hello, I have trouble with
    Dispatchers.Main
    on Android. Here are my dependencies:
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.1")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.1")
    And on my activity, a simple launch would do nothing when ran on
    Dispatchers.Main
    , whereas it works on `Dispatchers.IO`:
    GlobalScope.launch(Dispatchers.Main) { // Works with <http://Dispatchers.IO|Dispatchers.IO>
                Timber.d("Current thread: ${Thread.currentThread().name}")
            }
    In debug, I can access
    Dispatchers.Main
    which is correctly plugged to the android handler. Any idea what I'm doing wrong?
    t
    • 2
    • 1
  • p

    Paul Woitaschek

    05/03/2019, 9:01 AM
    I have an espresso test which fails because at the start of my fragment, I call
    launch(Dispatchers.Main) { ... withTimeoutOrNull(1000) }
    When I set that timeout to
    0
    , the tests passes because the views are ready. Now I thought, that in my tests I can set the main dispatcher for advancing the time automatically (so that the timout is thrown immediately and don't need to adjust the production code for my tests):
    Dispatchers.setMain(TestCoroutineDispatcher())
    . However that doesn't work. Has someone and idea why and how I can fix it?
    j
    • 2
    • 1
  • g

    gmaciel

    05/03/2019, 9:25 AM
    Hello everyone, is it ok to use
    CoroutineScope.rxObservable
    in production to gradually migrate Rx code into coroutines? Or since it's experimental should wait a little bit and find a different strategy for migration?
    g
    • 2
    • 1
  • n

    nwh

    05/04/2019, 12:58 AM
    Not sure if this is the best place to post, but I thought
    Flow
    could use a
    chunked
    method, just like
    List
    has:
    fun <T> Flow<T>.chunked(size: Int) = flow {
    	val list = mutableListOf<T>()
    	collect {
    		list.add(it)
    		
    		if (list.size == size) {
    			emit(list.toList())
    			list.clear()
    		}
    	}
    	
    	if (list.isNotEmpty())
    		emit(list)
    }
    Might be good to include in the standard library. Loving the API 👍🏻
    l
    • 2
    • 2
  • h

    Hexa

    05/04/2019, 6:49 AM
    Anyone got any video tutorials that explains how
    Flow
    works? I cant seem to find anything on YouTube
    t
    s
    • 3
    • 3
  • s

    Sam

    05/04/2019, 2:53 PM
    Is there any support for priority by coroutines?
    e
    r
    • 3
    • 11
  • d

    Dico

    05/04/2019, 5:58 PM
    Developers are recommended to use non-suspend
    fun CoroutineScope.xxxAsync()
    for functions that launch something and return immediately, and
    suspend fun xxx()
    for functions that suspend/block until all of their execution completes. Much of the kotlinx.coroutines API uses lambdas that are suspend and have a
    CoroutineScope
    receiver. The
    CoroutineScope
    allows developers to write coroutines with cancellability in mind - by checking
    isActive
    . What's the best way to get access to this in a
    suspend fun
    ?
    l
    • 2
    • 4
  • p

    Paul Woitaschek

    05/06/2019, 2:34 PM
    I have a situation where collect emits in the cancelled state:
    launch {
          state.collect {
            Timber.i("isActive=$isActive, job=$Job")
            render(it)
          }
        }
    It prints
    isActive=false
    . How is that possible?
    s
    v
    • 3
    • 20
  • s

    streetsofboston

    05/06/2019, 2:58 PM
    Quick question, and hopefully a quick answer 🙂 : How does one terminate a
    Flow<T>
    (successfully or with an error)? The
    FlowCollector<T>
    only has an
    emit
    method.
    d
    p
    j
    • 4
    • 15
  • s

    spierce7

    05/06/2019, 7:13 PM
    @elizarov Any news as to when we're going to see anything for Kotlin/native `Channel`'s?
    s
    • 2
    • 1
  • j

    Jan Skrasek

    05/07/2019, 12:24 PM
    I want to run multiple async tasks that doesn't affect each other neither their parent. Eg. something like:
    (0..4)
    	.map { async { .... } }
    	.forEach {
    		try  { 
    			it.await()...process
    		} catch() {}
    	}
    Which coroutine scope builder I should use? Using
    coroutineScope {}
    or
    supervisorScope {}
    would cancel the parent or siblings respectively.
    d
    n
    • 3
    • 3
  • w

    william

    05/07/2019, 12:50 PM
    if i have two blocking operations that I want to run in
    withContext
    , am I able to run these in parallel rather then serially?
    p
    d
    • 3
    • 5
  • s

    Samer Hobeika

    05/07/2019, 6:49 PM
    i’m thinking of this:
    GlobalScope.async {
      CallA() {
      if (it.success) {
       GlobalScope.async { CallB( it.value) }
     else { LogError() }
    } }
    😱 2
    b
    d
    • 3
    • 3
  • l

    louiscad

    05/07/2019, 11:45 PM
    Frankly, I'm wondering if
    GlobalScope
    should not be made experimental with something like
    @WhyGlobalThingsAreBad
    with some details on that special coroutines case of structured concurrency that should not be broken…
    ➕ 2
    g
    i
    p
    • 4
    • 8
  • m

    Marko Mitic

    05/08/2019, 12:28 PM
    Is there a way to check whether coroutine (scope) was canceled from a suspend function (that function not being extension of the scope)?
    a
    g
    g
    • 4
    • 40
  • s

    Sam

    05/08/2019, 1:49 PM
    Any ideas of how to convert this ValueCallback into suspend? evaluateJavascript needs to be called from the main thread failing to do so throws an exception ( All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 2) {3acde0b} called on null, FYI main Looper is Looper (main, tid 2) {3acde0b}))
    return suspendCoroutine { cont ->
                webView.evaluateJavascript( string ) { result ->
                    cont.resume( result )
                }
            }
    s
    • 2
    • 4
  • s

    Samer Hobeika

    05/08/2019, 5:12 PM
    How can we use the result of a first routing to call the 2nd one (reformulating my previous question)
    b
    s
    • 3
    • 18
  • z

    zak.taccardi

    05/08/2019, 7:22 PM
    What’s the reasoning that
    Channel<T>
    and
    Flow<T>
    don’t share the same backing interface? It seems unfortunate that the two won’t be able to share the same operators
    e
    a
    +2
    • 5
    • 14
  • s

    streetsofboston

    05/08/2019, 8:00 PM
    Sorry if I sound a bit like a broken record 🙂 but I’m struggling with handling exceptions when using `CoroutineScope.launch`: https://github.com/Kotlin/kotlinx.coroutines/issues/1157 I think there is either something wrong or I don’t understand the exception handling correctly. Could someone help me understand what’s going on? Thanks!
    m
    • 2
    • 5
  • s

    serebit

    05/08/2019, 9:14 PM
    Is it in any way possible to clean up resources from within a coroutine when a SIGINT signal is received (without using a shutdown hook)? I'm trying to do this in a multiplatform project, and it seems like the program is just ignoring anything I put in a
    finally
    block because coroutines don't block the program from exiting.
    d
    b
    • 3
    • 10
  • l

    louiscad

    05/09/2019, 3:57 PM
    Hi, did anyone combine the values from several `ReceiveChannel`s? What approach did you take?
    k
    d
    +6
    • 9
    • 25
Powered by Linen
Title
l

louiscad

05/09/2019, 3:57 PM
Hi, did anyone combine the values from several `ReceiveChannel`s? What approach did you take?
k

kevin.cianfarini

05/09/2019, 4:46 PM
You could create a subclass of channel that takes vararg amounts of channels as a constructor param. For each channel, create a coroutine and
recieve
the element from that channel. Each time you receive,
send
to
this
channel
d

Dominaezzz

05/09/2019, 5:15 PM
I usually redesign. If I can't be arsed I use
select
.
👍 1
p

Paul Woitaschek

05/09/2019, 6:24 PM
Use asFlow and then combineLatest
b

bj0

05/09/2019, 8:45 PM
I use to use
select
in a
produce
, but I haven't looked at any of the new
Flow
stuff
l

louiscad

05/09/2019, 10:24 PM
Oh, I forgot to mention that all channels have different types and that I want to combine them into a data class sent/broadcast to a new channel each time one new value is received
g

gaetan

05/09/2019, 10:44 PM
@louiscad is asking a question on coroutines channel. Must be a tough one. Sorry for the noise. 😉
😅 1
b

bohsen

05/10/2019, 5:53 AM
@gaetan Pretty sure he'll ace the implementation though. 😜 Also sorry for noise.
🤔 1
b

bj0

05/10/2019, 5:57 AM
again, fairly easy to do with
select
and
produce
l

louiscad

05/10/2019, 7:23 AM
My current implementation is 47 lines of boilerplate code (not counting imports, no comments/KDoc lines) to combine 4 channels, each of different element types into a data class broadcast in a new
ConflatedBroadcastChannel
. I wish I could have a shorter solution that could scale better, that's why I asked. Also, I have no clue how I can do this with
select
and
produce
.
d

Dominaezzz

05/10/2019, 8:20 AM
What do you mean by combine? You want to get an item from each one, put all the items in a data class with 4 fields and then return the instance? Why not just call receive on each channel. Or you want to wait for the the first item from any channel and return a transformation/map of the item?
l

louiscad

05/10/2019, 10:22 AM
For now, that's what I do, I have a call to receive for each channel, I keep the last received value and each time I receive on new value for any of each channel, I update the last value and update the data class for all last values to be broadcast. I wish I found a more generic or less verbose way to do it for just 4 channels. It's basically over 10 lines of code per channel for now, and I use a few extensions
d

Dominaezzz

05/10/2019, 10:26 AM
How about
DataClass(channel1.receive(), channel2.receive(), channel3.receive(), channel4.receive())
?
l

louiscad

05/10/2019, 10:28 AM
I also need updates, when only one of the channels produces a new value, I need a new dataclass with the last values previously received from the other channels.
d

Dominaezzz

05/10/2019, 10:30 AM
Oh I get it now, you need a stream of latest values.
https://pl.kotl.in/AGzcQBHsL . Doesn't handle input channels closing though.
❤️ 1
b

bj0

05/11/2019, 7:26 AM
Yea that's basically what I had in my mind, but with
= produce {
👍 1
l

louiscad

05/13/2019, 7:43 AM
Here's a rather generic approach inspired by the snippet Dominic shared:
fun <E1, E2, R> CoroutineScope.combineLatest(
    one: ReceiveChannel<E1>,
    two: ReceiveChannel<E2>,
    transform: (one: E1, two: E2) -> R
): ReceiveChannel<R> {
    val output = Channel<R>(capacity = Channel.CONFLATED)
    output.invokeOnClose {
        one.cancel()
        two.cancel()
    }
    launch {
        var latestOne: E1 = one.receive()
        var latestTwo: E2 = two.receive()
        output.send(transform(latestOne, latestTwo))
        while (true) {
            select<Unit> {
                one.onReceive { latestOne = it }
                two.onReceive { latestTwo = it }
            }
            output.send(transform(latestOne, latestTwo))
        }
    }.invokeOnCompletion {
        one.cancel()
        two.cancel()
    }
    return output
}
(Edited to return
ReceiveChannel<T>
.) Do you think it's correct, especially regarding closing handling?
p

Paulius Ruminas

05/13/2019, 7:51 AM
If one or two channel gets cancelled
var latestOne: E1 = one.receive()
var latestTwo: E2 = two.receive()

select<Unit> {
        one.onReceive { latestOne = it }
        two.onReceive { latestTwo = it }
}
then these statements will throw
CancellationException
. Is this the behaviour you want?
l

louiscad

05/13/2019, 8:11 AM
Yes, that shouldn't be a problem since it'll be eaten by
launch
. I should cancel the two other channels though. I edited the snippet to return
ReceiveChannel<T>
BTW.
I also edited to cancel the channels on scope completion.
p

Paulius Ruminas

05/13/2019, 8:21 AM
Yes, that shouldn't be a problem since it'll be eaten by
launch
But it will cancel the whole scope if it is not
Supervised
.
runBlocking {
            val a = produce {
                while (true) {
                    delay(1_000)
                    send(1)
                }
            }
            val b = produce {
                while (true) {
                    delay(2_000)
                    send(2)
                }
            }

            coroutineScope {
                launch {
                    while (true) {
                        println("Test")
                        delay(1_000)
                    }
                }

                launch {
                    combineLatest(a, b) { a, b -> Pair(a, b) }.consumeEach {
                        println(it)
                    }
                }

                delay(10_000)
                a.cancel()
            }
        }
When
a.cancel()
is called it will throw an
Exception
and cancel the coroutine that prints "Test".
l

louiscad

05/13/2019, 8:25 AM
This:
runBlocking {
    launch {}.cancel()
}
doesn't throw because cancellation is not a crash, so it doesn't propagate to parent scope when the coroutine is concurrent (as with
launch
or
async
). So I don't see a problem here.
d

Dico

05/13/2019, 3:57 PM
@louiscad if one channel receives 2 items before the other receives any, does your solution drop the second item for the first channel? Depends on
onReceive
behaviour.
d

Dominaezzz

05/13/2019, 6:05 PM
If this is the only receiver, it doesn't.
l

louiscad

05/13/2019, 6:18 PM
@Dico The second value would not be received until the select is reached, and then, it'd be received immediately (unless the other channel has a value that is selected first because of bias), and would trigger a new transform and sending.
View count: 4