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

    David Glasser

    08/28/2019, 6:00 AM
    I'm confused by how to properly use CoroutineExceptionHandler. I tried:
    import kotlinx.coroutines.CoroutineExceptionHandler
    import kotlinx.coroutines.coroutineScope
    import kotlinx.coroutines.launch
    import kotlinx.coroutines.runBlocking
    import kotlin.system.exitProcess
    
    fun main() = runBlocking {
    	val handler = CoroutineExceptionHandler { _, t ->
    		println("handling exception: $t")
    		exitProcess(1)
    	}
    	coroutineScope {
    		launch(handler) {
    			println("running")
    			throw Exception("OMG")
    		}
    	}
    	Unit
    }
    I would expect this to print "handling exception" and exit the process. Instead it shows that an exception was unhandled in
    main
    (I'll paste in the thread)
    g
    • 2
    • 4
  • s

    svenjacobs

    08/28/2019, 7:30 AM
    Hi all, I'm currently trying to replace usages of
    Channel
    with
    Flow
    in my Android application. But now I'm stuck in a conceptual thinking problem: Right now I use
    Channel
    to handle UI events on Android views, for instance clicks inside a
    RecyclerView.Adapter
    . I create an instance of
    Channel
    in the view (or presenter, it doesn't matter) and pass it to the
    RecyclerView.Adapter
    . Then inside the adapter I could just pass click events to the channel. But with
    Flow
    , the flow needs to be created at the place where the data is emitted. However I don't want to have x flows in my Adapter for every view the adapter manages. Is
    Flow
    even suited for UI events or are UI events classically hot streams? Am I just trying to apply
    Flow
    where
    Channel
    is the right choice after all?
    b
    d
    +3
    • 6
    • 19
  • m

    myanmarking

    08/28/2019, 2:13 PM
    i tried onStart but obviously, it still is debounced
    v
    • 2
    • 8
  • m

    myanmarking

    08/28/2019, 2:25 PM
    don't know if its the most efficient tho. but it seems to work
    d
    • 2
    • 1
  • i

    Ive Vasiljevic

    08/28/2019, 6:01 PM
    is liveData block still a thing? I can't seem to use it even when I implement everything that is needed.
    m
    • 2
    • 3
  • p

    Pere Casafont

    08/29/2019, 2:04 PM
    I have a service that uses ktor + websockets + broadcast channel. After some hours it stops responding to http requests and
    sayX()
    GlobalScore.launch(Dispatchers.Default) { sayY() }
    triggers X but not Y... it looks like the whole coroutines engine goes down. Is that possible?
    d
    d
    +2
    • 5
    • 32
  • l

    Laura de la rosa

    08/29/2019, 2:37 PM
    Hi!, all... which is the difference between GlobalScope.async and CoroutineScope(context).launch?? can someone explain me
    d
    s
    +2
    • 5
    • 34
  • i

    ivan.savytskyi

    08/29/2019, 6:22 PM
    Hey folks, is there any easy way to auto close the BroadcastChanel as soon as the last subscribed channel is closed?
    🇳🇴 2
    p
    g
    • 3
    • 2
  • s

    svenjacobs

    08/30/2019, 6:15 AM
    Good morning, is there an operator for concatenating two `Flow`s, something like:
    val flow1 = flowOf(1, 2, 3)
    val flow2 = flowOf(4, 5, 6)
    val flow3 = flow1.concat(flow2) // = 1, 2, 3, 4, 5, 6
    The order of
    flow3
    does not matter here, so it also might be
    1, 4, 2, 5, 3, 6
    or any other order, depending on how the values are produced in
    flow1
    and
    flow2
    .
    l
    m
    • 3
    • 8
  • t

    thana

    08/30/2019, 6:38 AM
    On the JVM the Default and IO dispatchers are backed by fixed-size threadpool? right? according to the java docs of
    newFixedThreadPool
    it is backed by an unbounded job queue. is that true for our dispatchers, too?
    s
    l
    • 3
    • 8
  • r

    roy

    08/30/2019, 7:49 AM
    Hi, what is the canonical way to create a flow that replays its history whenever it's subscribed to? I have a Flow<String> that contains some log lines and whenever someone calls my API I'd like it to publish all previous log lines and additionally any new ones, by returning the flow as a server-sent event
    o
    s
    • 3
    • 4
  • s

    sunbreak

    08/30/2019, 11:37 AM
    Hi, guys, is there any API in
    Flow
    like
    Observable.timeout
    ?
    m
    g
    • 3
    • 11
  • a

    asad.awadia

    08/30/2019, 9:35 PM
    What is the use case for flows?
    z
    g
    • 3
    • 26
  • z

    zak.taccardi

    08/31/2019, 12:04 AM
    I want the subject version of a flow (a flow I can force to emit). Does this exist yet? or do I need to back it with an external channel for now?
    private val channelA = Channel<Int>()
    private val channelB = Channel<Int>()
    private val flowA: Flow<Int> = channelA.consumeAsFlow()
    private val flowB: Flow<Int> = channelB.consumeAsFlow()
    suspend fun whenSourceAEmits(value: Int) {
        channelA.send(value)
    }
    suspend fun whenSourceBEmits(value: Int) {
        channelB.send(value)
    }
    o
    • 2
    • 1
  • s

    sunbreak

    08/31/2019, 5:13 AM
    Somehow, the
    withTimeout
    doesn’t work on iOS without
    runBlocking
    . Is there another way round?
    b
    • 2
    • 11
  • s

    spierce7

    08/31/2019, 5:11 PM
    The documentation for
    <http://Dispatchers.IO|Dispatchers.IO>
    says:
    This dispatcher shares threads with a [Default][Dispatchers.Default] dispatcher, so using
    `withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }` does not lead to an actual switching to another thread &mdash;
    typically execution continues in the same thread.*
    This behavior seems wrong to me. Isn’t the goal of
    <http://Dispatchers.IO|Dispatchers.IO>
    to keep
    Dispatchers.Default
    threads free. Sharing threads between the dispatchers seems counterintuitive to this goal.
    m
    t
    +2
    • 5
    • 20
  • v

    Vans239

    08/31/2019, 9:36 PM
    Hi folks. I am confused with
    withTimeout
    . I have a function which can block the thread for undefined time. The caller should get timeout exception after timeout. The function doesn't support cancellation. There is a similar case, but it doesn't work as described. https://stackoverflow.com/questions/47635367/kotlin-coroutines-with-timeout/47641886#47641886 The snippet behind blocks for 10 seconds.
    runBlocking {
       val work = async { Thread.sleep(10000) }
       withTimeout(100) {
            work.await()
       }
    }
    There are 3 solutions, which helps to make it working: - use
    GlobalScope.async
    - use
    async(NonCancellable + <http://Dispatchers.IO|Dispatchers.IO>)
    . Scope will await for async result if i don't specify
    NonCancellable
    .
    <http://Dispatchers.IO|Dispatchers.IO>
    is needed because
    runBlocking
    is single threaded. - use custom
    scope
    Am I missing something? Is there simpler approach?
    d
    • 2
    • 8
  • t

    tseisel

    09/01/2019, 7:14 PM
    I'd like to Unit Test the following class :
    class MyClass(private val scope: CoroutineScope) {
         // launches new coroutines in the passed scope 
    }
    Some of my test scenarios requires that the passed
    CoroutineScope
    be cancelled. How would you write such test with
    runBlockingTest
    ?
    e
    • 2
    • 2
  • u

    Uchun Lee

    09/01/2019, 11:07 PM
    I want to get Result<T> class(or something like it) after finished launch block. Because I used invokeOnCompletion with CoroutineExceptionHandler. But It is not enough for me. There is no value of success case. So I made this code. But I want to find a better way. If somebody knows a better way. comment please.
    launchCatching(
        block = {
            getRandomNumber()
        },
        result = {
            println("result is $it")
        }
    ).invokeOnCompletion {
        it is Throwable
    }
    
    fun <T> CoroutineScope.launchCatching(
        context: CoroutineContext = EmptyCoroutineContext,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        block: suspend CoroutineScope.() -> T,
        result: (result: Result<T>) -> Unit
    ) = launch(context, start) {
        result(
            runCatching {
                block()
            }
        )
    }
    
    fun <T> CoroutineScope.launchCatching(
        context: CoroutineContext = EmptyCoroutineContext,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        block: suspend CoroutineScope.() -> T,
        onSuccess: (value: T) -> Unit,
        onFailure: (exception: Throwable) -> Unit
    ) = launch(context, start) {
        runCatching {
            block()
        }.fold(
            onSuccess,
            onFailure
        )
    }
    d
    e
    • 3
    • 6
  • n

    necati

    09/01/2019, 11:19 PM
    https://android.jlelse.eu/rxbus-kotlin-listen-where-ever-you-want-e6fc0760a4a8 Hello all, how can I create an event bus like this with current coroutine apis?
    o
    a
    • 3
    • 13
  • t

    thana

    09/02/2019, 2:22 PM
    i have a
    fun
    that creates a
    CoroutineExceptionHandler
    . when i do
    launch(exceptionHandler()){throw RuntimeException()}
    it gets called but with
    runBlocking
    the exception is not caught. is that expected behavior?
    d
    • 2
    • 4
  • p

    Paulius Ruminas

    09/02/2019, 4:05 PM
    Hello, how can I make forEach continue even if some elements get cancelled e.g.
    @Test
        fun example() = runBlockingTest {
            val actual = mutableListOf<Int>()
    
            launch {
                (0..5).forEach { i ->
                    supervisorScope {
                        if (i == 1) cancel()
                        actual.add(i)
                    }
                }
            }
    
            assertEquals(listOf(0, 2, 3, 4, 5), actual)
        }
    d
    • 2
    • 4
  • k

    Kroppeb

    09/02/2019, 6:48 PM
    I have a
    kotlinx.coroutines.io.ByteReadChannel
    . How do I read a utf8String of certain length?
    d
    • 2
    • 9
  • s

    synhershko

    09/03/2019, 7:50 AM
    Seems like this something to do with the Channel buffer (when exists)? Is there any reason the buffered messages will not be delivered?
    d
    • 2
    • 2
  • t

    tseisel

    09/03/2019, 5:28 PM
    Is it possible to re-open a cancelled/failed
    BroadcastChannel
    ? I'd like to re-execute the block passed to
    broadcast
    when receiving from it after being closed :
    val channel = broadcast<String>(capacity = Channel.CONFLATED, start = LAZY) {
        val callback = object : Subscription {
            override fun onValue(value: String) {
                // May be called multiple times.
                offer(value)
            }
            override fun onError(error: Exception) {
                close(error)
            }
        }
    
        subscribe(callback)
        awaitClose { unsubscribe(callback) }
    }
    
    // At some point in time, receive latest value from the channel. 
    // Because the broadcast is lazy, this registers a callback and wait for a value.
    // Lets assume that the callback failed, the exception is rethrown here.
    channel.consume { receive() }
    
    // At a later time, I'd like "receive" to re-execute the producer coroutine, re-registering a new callback.
    channel.consume { receive() }
    z
    d
    • 3
    • 8
  • d

    David Glasser

    09/03/2019, 6:27 PM
    We're using JUnit and doing the pattern where we write lots of tests like
    @Test fun foo = runBlocking {
    . (We haven't tried using
    runBlockingTest
    since we haven't needed the extra time-related power it brings — but maybe this is the answer to our issue?) A problem we've been running into is that it's quite easy to have a test whose final line doesn't return Unit. Then the runBlocking doesn't return Unit and neither does the test function, and JUnit just skips it. There is an IntelliJ inspection for this at least but it seems like a bit of a pain. What do people do for this?
    @Test fun foo: Unit = runBlocking {
    ?
    @Test fun foo() { runBlocking {
    ? Something else?
    s
    t
    s
    • 4
    • 18
  • p

    Pablichjenkov

    09/03/2019, 8:57 PM
    Whats the closest equivalent to below code using
    Flow
    . Or in other words the
    create
    and
    just
    operator equivalents.
    Observable
    		.create(
    			{ emitter: Emitter<Boolean> ->
                                     // Do stuff and onNext
                            },
    			Emitter.BackpressureMode.BUFFER
                      )
    
    // Also for this 
    
    Observable.just(true)
    I am using bellow builder but wanted to see other alternatives
    flow { flowCollector -> ...// Do stuff and emit }
    e
    p
    g
    • 4
    • 14
  • k

    kevin.cianfarini

    09/03/2019, 9:29 PM
    is there a way to get the associated
    Job
    from a coroutine context?
    d
    g
    • 3
    • 10
  • c

    coder82

    09/04/2019, 8:47 AM
    What happens if I use withContext(Dispatchers.IO) and execute a lot of calls, is there a limit? what if all the threads are busy spinning? How to provide backpressure? Don't want to reach out of memory. @gildor
    g
    • 2
    • 33
  • r

    rkeazor

    09/04/2019, 11:41 AM
    When should one use async-await Vs withContext
    m
    l
    d
    • 4
    • 10
Powered by Linen
Title
r

rkeazor

09/04/2019, 11:41 AM
When should one use async-await Vs withContext
m

marstran

09/04/2019, 11:48 AM
Calling
withContext
is like doing
await
immediately on the
Deferred
from
async
. Use
async
if you want to do something else while waiting for the
Deferred
to complete.
👍🏼 2
l

louiscad

09/04/2019, 12:09 PM
Not exactly. A crash in the
async
block will cancel the parent scope.
withContext
will only throw and will let you catch without an extra scope.
r

rkeazor

09/04/2019, 12:09 PM
Makes sense , Thanks!
Ahhhhh
I see , thanks @louiscad!
So depending how you want your cancellation will be how you choose one from the other
So depending how you want your cancellation will be how you choose one from the other
l

louiscad

09/04/2019, 1:22 PM
@rkeazor Nope, I'll always using
withContext
if I need to change the dispatcher. The only exception might be using
flowOn
to make a flow run on a specific dispatcher.
async
is for parallelization in a coroutine.
➕ 1
👍 1
d

Dominaezzz

09/04/2019, 3:46 PM
cough concurrency not parallelism cough
l

louiscad

09/04/2019, 5:45 PM
I see it as local parallelism. The issue is the connotation of these words that I want to avoid. Concurrency is more loaded of it IMHO.
View count: 7