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

    Romain

    03/11/2019, 2:15 PM
    Hello, I'm wondering where is it best on Android to launch a coroutine for a simple post to a server. Let's say I have a button on a Fragment that call a function in a Viewmodel that call a function in a Repository. Should I launch the coroutine in the Fragment, the Viewmodel or the Repository?
    w
    d
    • 3
    • 5
  • k

    kevin.cianfarini

    03/11/2019, 3:00 PM
    Does anyone know of some good articles where a suspending function is written that deals with something like IO? I want to learn about composing a suspending function from resources which aren't suspending
    m
    • 2
    • 13
  • g

    giso

    03/11/2019, 4:14 PM
    Hi there. I have a suspend function in which a resource is opened and later closed in a finally block. Upon cancellation I would expect to receive a CancellationException. But I don't receive any und the finally block is not executed. Does anyone know why?
    a
    • 2
    • 4
  • s

    sbyrne

    03/11/2019, 8:30 PM
    Seems like I should be able to wrap a ReceiveChannel in a Sequence to pass it to another library.
    o
    d
    • 3
    • 7
  • o

    obobo

    03/11/2019, 11:12 PM
    Hello, I've run into a problem throwing an exception from inside
    runBlocking
    block. I have a test in which I mock an external service integration throwing an exception. Via
    runBlocking
    I call the suspending function, which in turn creates a new CoroutineScope using
    CoroutineScope(coroutineContext + <http://Dispatchers.IO|Dispatchers.IO>)
    and creates many deferred calls using
    async
    to the mocked external service, then uses
    awaitAll()
    to get their results. Surrounding this code is a try/catch block, which handles the exception. I've stepped in and all of this is working fine. The problem is when the suspending function returns, the surrounding block declares it exited exceptionally and throws an exception from the runBlocking call. Since I'm handling the exception, what's the right way to prevent the context from picking up the exception?
    s
    • 2
    • 4
  • d

    Dmytro Danylyk

    03/12/2019, 5:02 AM
    Hi. I have an issue with
    async
    ,
    coroutineScope
    and exception handling. When
    coroutineScope
    is moved into separate function, I am able to catch exception inside coroutine. When
    coroutineScope
    is declared inside coroutine, I am not able to catch exception. This code works fine:
    suspend fun doWork(): Deferred<String> = coroutineScope {
            async(<http://Dispatchers.IO|Dispatchers.IO>) {
                throw IllegalArgumentException()
            }
        }
    
        // works fine
        fun loadData() = scope.launch {
            try {
                doWork().await()
            } catch (e: Exception) {
                // exception is caught here
            }
        }
    This doesn’t.
    // crash FATAL EXCEPTION: DefaultDispatcher-worker-3 @coroutine#1
    fun loadData() = scope.launch {
        try {
            val deferred = coroutineScope {
                scope.async(<http://Dispatchers.IO|Dispatchers.IO>) {
                    throw IllegalArgumentException()
                }
            }
            deferred.await()
        } catch (e: Exception) {
            // exception is NOT caught here
        }
    }
    g
    • 2
    • 12
  • m

    Martin Devillers

    03/12/2019, 2:29 PM
    What do you think about the naming of the
    close
    method on
    SendChannel
    ? IMO it’s a bit confusing, because it brings up the idea of a
    Closeable
    , which is very different (especially since there are plenty of channels which don’t need to be closed because they send indefinitely). The documentation leads me to suggest something like
    sendLast
    , which I think would convey the intent better.
    s
    e
    • 3
    • 7
  • h

    hmole

    03/13/2019, 7:01 AM
    Anyone has a gist or any suggestions on how to implement a
    sample
    operator from RX on a
    Channel
    ? I need to discard items from the channel if they come at the higher rate than I specify.
    s
    • 2
    • 5
  • a

    Aaron Stacy

    03/13/2019, 1:45 PM
    👋 Hi all! Say I want something like
    suspend fun request(url: URL): MyDataClass
    , but I want to cache the HTTP results so I don’t make requests twice. Anyone know a good example of how to do that? @elizarov’s excellent post https://medium.com/@elizarov/deadlocks-in-non-hierarchical-csp-e5910d137cc has a nice example, but the only way I can think to wrap the channels in a suspend function is using `Deferred`’s. Is that the way to do it? It feels clunky.
    w
    • 2
    • 3
  • a

    ahulyk

    03/13/2019, 2:31 PM
    Hi all! What is the difference between Job and SupervisorJob in case of Exception Handling?
    class Presenter() : CoroutineScope {
            private val job = Job()
    
            override val coroutineContext: CoroutineContext
                get() = job + Dispatchers.Main
    
            override fun onDestroy() {
                job.cancel()
            }
    
            fun loadData() {
                launch {
                    try {
                        //loadData().async()
                    } catch (e: Exception) {
                        //handle exception
                    }
                }
    
            }
        }
    class Presenter() : CoroutineScope {
            private val job = SupervisorJob()
    
            override val coroutineContext: CoroutineContext
                get() = job + Dispatchers.Main
    
            override fun onDestroy() {
                job.cancel()
            }
    
            fun loadData() {
                launch {
                    try {
                        //loadData().async()
                    } catch (e: Exception) {
                        //handle exception
                    }
                }
    
            }
        }
    g
    • 2
    • 18
  • g

    ghedeon

    03/13/2019, 8:31 PM
    Correct me if I'm wrong, but usage of
    fun CoroutineScope.foo()
    basically kills the usage of Mockito in my project, right? It has some support for suspended functions, but not extensions. So,
    mockk
    is the only answer or there are workarounds? That's quite a change for a big codebase...
    v
    • 2
    • 2
  • a

    ansman

    03/13/2019, 9:10 PM
    What’s the idiomatic way of canceling
    runBlocking
    ? I’m bridging a blocking API that gives me a
    CancelationSignal
    that can notify when canceled
    g
    • 2
    • 4
  • o

    oday

    03/14/2019, 1:48 PM
    no more need for proguard-rules and it shrinks to even more than proguard
    w
    • 2
    • 3
  • a

    Aaron Stacy

    03/14/2019, 4:01 PM
    If I'm adapting some I/O (
    HttpURLConnection
    , reading an
    InputStream
    ) to a coroutine, it seems like I'd want to do something to suspend the coroutine while waiting on the network or disk. Is there a good example of this?
    a
    • 2
    • 1
  • j

    jw

    03/14/2019, 4:08 PM
    encapsulate all the work and run it with
    async(IO) { .. }
    l
    • 2
    • 1
  • l

    louiscad

    03/14/2019, 6:13 PM
    async
    is only for parallelization. I avoid recommending it unless you need it because I saw a lot of misuse regarding it that broke structured concurrency and throwables handling.
    z
    • 2
    • 2
  • j

    jw

    03/14/2019, 6:40 PM
    still, don't use Future. it's like top 3 worst JDK types
    👍 5
    ➕ 1
    s
    g
    • 3
    • 3
  • o

    Oleh Ponomarenko

    03/15/2019, 11:08 AM
    Have you ever seen some analytic of launching some jobs in different Dispatchers (Main, Default, IO)? I know the difference between these dispatchers. I'm just interested in comparable data.
    a
    g
    • 3
    • 13
  • m

    Martin Devillers

    03/15/2019, 1:27 PM
    Would it seem reasonable to add
    object InactiveScope
    the standard library, which would be a
    CoroutineScope
    instance with an job always in a cancelled state? I think this would be useful in cases when we have a scope var which isn’t initialized at object creation, so we could use this object as a placeholder rather than using a null value. I’m thinking about scopes tied to Android activity states, i.e.
    activityCreatedScope
    ,
    activityStartedScope
    ,
    activityResumedScope
    . Currently the solutions are to use
    lateinit
    or nullable
    var
    .
    s
    e
    g
    • 4
    • 11
  • d

    davidasync

    03/15/2019, 2:38 PM
    Hello can anyone explain the differences between kotlin coroutines and java NIO ?
    m
    • 2
    • 2
  • s

    spierce7

    03/15/2019, 7:28 PM
    Can anyone explain why this coroutine doesn't just emit values forever? Instead count gets to ~20, and then I stop receiving values on the BroadcastChannel. Either this is a bug, or I'm misunderstanding a core concept of how coroutines cancel.
    d
    s
    • 3
    • 15
  • s

    SUPERCILEX

    03/15/2019, 9:59 PM
    It seems like if an exception is raised in some background thread from Java code and passed through the coroutines funnel, you get useless stuff like this:
    Fatal Exception: java.net.SocketTimeoutException: timeout
           at okio.Okio$4.newTimeoutException(Okio.java:232)
           at okio.AsyncTimeout.exit(AsyncTimeout.java:275)
           at okio.AsyncTimeout$2.read(AsyncTimeout.java:243)
           at okio.RealBufferedSource.indexOf(RealBufferedSource.java:354)
           at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:226)
           at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215)
           at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
           at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
           at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
           at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
           at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
           at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
           at support.bymason.magicwand.core.data.PlatformRequestsKt$client$1.intercept(PlatformRequests.kt:18)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
           at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
           at okhttp3.RealCall$AsyncCall.execute(RealCall.java:2254)
           at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
           at java.lang.Thread.run(Thread.java:818)
    g
    • 2
    • 4
  • s

    SUPERCILEX

    03/15/2019, 10:03 PM
    Any tips for the kind of breadcrumbs I could be tossing around?
    d
    g
    • 3
    • 15
  • j

    Jemshit Iskenderov

    03/16/2019, 6:30 AM
    Hi, i have confusion when using
    CoroutineScope.cancel()
    and
    CoroutineScope.job.cancel()
    . Here is the CoroutineScope:
    val scope = object : CoroutineScope {
            val parentJob = Job()
            override val coroutineContext: CoroutineContext
                get() = parentJob + <http://Dispatchers.IO|Dispatchers.IO> 
    }
    Observation 1: when Job of CoroutineScope is cancelled, both seemed not active:
    scope.launch {
            withContext(Dispatchers.Default) {
                println("result")
            }
            scope.parentJob.cancel()
            println("isActive:$isActive, job.isActive:${scope.parentJob.isActive}")
    
            // PRINTS isActive:false, job.isActive:false
    }
    Observation 2: when CoroutineScope is cancelled, only CoroutineScope.isActive seems false. Job.isActive is true
    scope.launch {
            withContext(Dispatchers.Default) {
                println("result")
            }
            cancel()
            println("isActive:$isActive, job.isActive:${scope.parentJob.isActive}")
    
            // PRINTS isActive:false, job.isActive:true
    }
    Observation 3 (CoroutineScope for Android Fragment):
    protected lateinit var job: Job
    override val coroutineContext: CoroutineContext
            get() = Dispatchers.Main + job
    
    launch {
        val result = withContext(Dispatchers.Default) {
              // ...
        }
        this@Fragment.job.cancel()
        // Log.d("$isActive ${this@Fragment.job.isActive}")
        // PRINTS true, false
    }
    Question: when looking at source code,
    CoroutineScope.cancel
    and
    CoroutineScope.isActive
    calls methods of its Job. But in above code,
    CoroutineScope.cancel
    does not return
    Job.isActive
    or vice versa. Why this behavior? Is
    withContext
    changing something?
    d
    • 2
    • 11
  • h

    Hexa

    03/16/2019, 9:07 AM
    is there a better way to remove the
    if(carId.isNullOrEmpty())
    statement here as it looks duplicated code to me.
    deferredCarIdResult.await()
    can return an empty string like this "" so I return CarNotFound("not found") but when the coroutines timeout I also return CarNotFound("not found")
    val carId = runBlocking {
                        withTimeoutOrNull(10000L) {
                            deferredCarIdResult.await()
                        }
                    } ?: return CarNotFound("not found")
                    
                    if(carId.isNullOrEmpty()){
                        return CarNotFound("not found")
                    }
    d
    • 2
    • 9
  • j

    Jay

    03/16/2019, 12:43 PM
    When testing coroutines, is there a way to get notified on each context switch?
    l
    d
    • 3
    • 3
  • d

    davidasync

    03/16/2019, 12:46 PM
    Hello, http clients that utilize
    java NIO
    already have asynchronous nature for example Jetty Http Client, asynchttpclient, apache async http client, and etc is it necessary to wrap it with coroutines to do parallel http call ?
    d
    s
    d
    • 4
    • 7
  • d

    davidasync

    03/18/2019, 8:05 AM
    Is there any http client library that adopt NIO similar to
    java NIO
    but using coroutines (or another lightweight thread) instead of native thread ?
    t
    v
    • 3
    • 2
  • e

    Ellen Shapiro

    03/18/2019, 4:48 PM
    So I gave a talk about Kotlin/Native and I was under the impression that there was no
    runBlocking
    on K/N because I could never successfully get it to import. But @russhwolf pointed out that it is definitely there. I looked in my local
    kotlinx-coroutines-core-1.1.1
    and lo and behold, there it is. What am I missing about getting it to import in a
    common
    framework?
    r
    d
    • 3
    • 9
  • q

    qwert_ukg

    03/19/2019, 10:05 AM
    -.kt
    g
    • 2
    • 9
Powered by Linen
Title
q

qwert_ukg

03/19/2019, 10:05 AM
-.kt
g

gildor

03/19/2019, 10:07 AM
Is it spring? maybe better #spring
in general I would say that you shouldn’t use launch or use Unconfined dispatcher to return post result after you actaully saved data
q

qwert_ukg

03/19/2019, 10:10 AM
Thanks
What i should to use in my case? I want return message id immediately, which user will use to get result of message sending
coze
sendAndSaveResult(uuid, message)
take a lot of time
g

gildor

03/19/2019, 10:18 AM
But this is test, so it should be fine to wait
one more way is have some additional handler that will tell you when data is updated (it may be callback, Deferred or something like that)
q

qwert_ukg

03/19/2019, 10:18 AM
ok. i see
thanks a lot
View count: 3