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

    davidasync

    01/28/2019, 4:09 PM
    Hello guys, anyone already try integrate new relic with kotlin coroutines ? I change my scheduleExecutor to coroutines, but the data is not shown at new relic dashboard
    f
    • 2
    • 4
  • s

    svenjacobs

    01/29/2019, 7:01 AM
    Hi all, is it a good idea to pass around instances of
    CoroutineScope
    ? Let's say I have a function that calls
    launch
    . I could do it like this:
    fun doSomething() {
      GlobalScope.launch {
        ...
      }
    }
    but what if I want the
    launch
    block to be tied to the outer scope? So if the outer scope is terminated so should the
    launch
    block. What I tried is
    fun doSomething(scope: CoroutineScope) {
      scope.launch {
        ...
      }
    }
    but it doesn't feel right. Or should I better use
    suspend fun doSomething() {
      coroutineScope {
        launch {
          ...
        }
      }
    }
    but then I create a new scope, right?
    g
    • 2
    • 3
  • e

    elizarov

    01/29/2019, 7:19 AM
    It depends on what you want
    doSomething
    to do: • If you want to wait until it finishes doing its work you write
    suspend fun doSomething() = coroutineScope { ... }
    • If you want it to return quickly with a side effect of launching new coroutine, you write
    fun CoroutineScope.doSometing() = launch { ... }
    .
    s
    r
    s
    • 4
    • 13
  • r

    rrva

    01/29/2019, 7:22 AM
    Using coroutine syntax to make orchestration of API calls easier to read/write is something I found useful. I could easily see it be so useful that it should go into kotlinx-coroutines... Here I have blocking calls, but I still find coroutine syntax elegant and simple to reason about. Like this:
    private fun <A, B> Iterable<A>.parallelMap(context: CoroutineContext, f: suspend (A) -> B): List<B> = runBlocking {
            map { async(context) { f(it) } }.map { it.await() }
        }
    
    val listOfIds.parallelMap(fooApiPool) { fooApiClient.fetchStuff(it)}
    (found at: https://jivimberg.io/blog/2018/05/04/parallel-map-in-kotlin/) But what about orchestrating calls to several sources (clients calls could be made suspendable if this is important), where we for example have three source API:s which we would like to be called in parallel, and then the values are awaited and collected? (I'm trying to get rid of RxJava for some use-cases where I found it to be a burden to maintain/debug). What are good patterns here for expressing the execution flow?
    g
    • 2
    • 19
  • a

    ARnikev

    01/29/2019, 10:17 AM
    Hi everyone, I’m facing a quite strange problem with spring WebClient + coroutines integration. I have the following method with webclient invocation:
    fun doSomething(someBody: Body): Mono<Void> {
      return client
    			.patch()
    			.uri("/someuri")
    			.accept(APPLICATION_JSON_UTF8)
    			.contentType(APPLICATION_JSON_UTF8)
    			.body(BodyInserters.fromObject(someBody))
    			.retrieve()
    			.bodyToMono(Void::class.java)
    			.onErrorMap {
    				BusinessServiceException("CODE", "TITLE").apply {
    					httpStatus = HttpStatus.FORBIDDEN
    					detail = "some detail"
    				}
    			}
    }
    To invoke this method in non-blocking way i do following thing:
    try {
      clientBean.doSomething(someBody).awaitFirst()
    } catch (e: Exception) {
      throw e
    }
    What i expect is that in case of exception in webclient call there has to be BusinessServiceException caught in catch block above. And BusinessServiceException fields (code, title, httpStatus, detail) have to be populated with values that i’ve set in onErrorMap method on webclient mono response. What i really have is BusinessServiceException with null fields (code, title, httpStatus, detail) and cause field populated with expected by me BusinessServiceException (with all fields filled the same way as i’ve set them in onErrorMap method). BusinessServiceException class looks like this:
    public class BusinessServiceException extends ServiceException {
        public BusinessServiceException(String code, String title) {
            super(code, title);
        }
        public BusinessServiceException(String message, Throwable cause) {
            super(message, cause);
        }
    }
    I’ve tried to debug all this stuff and it seems like that BusinessServiceException’s constructors called 2 times. First time, as expected, the
    public BusinessServiceException(String code, String title)
    constructor is called, in onErrorMap() method. Second time, unexpectedly, the
    public BusinessServiceException(String message, Throwable cause)
    constructor is called, somewhere in
    private suspend fun <T> Publisher<T>.awaitOne -> override fun onError(e: Throwable) { cont.resumeWithException(e)}
    method, and that call wraps original exception in exception of the same type but with null fields (because of wrong constructor call). I couldn’t find the exact place where this constructor could be called. Interesting thing is if i delete this second constructor
    public BusinessServiceException(String message, Throwable cause)
    from the BusinessServiceException.class - everything works as expected. I would really appreciate any thoughts on this.
    e
    v
    • 3
    • 5
  • w

    withoutclass

    01/29/2019, 3:46 PM
    https://medium.com/@elizarov/structured-concurrency-722d765aa952
    i
    • 2
    • 1
  • t

    tseisel

    01/29/2019, 9:03 PM
    I have watched the "Kotlin Coroutines in Practice" talk by Roman Elizarov and learned about the Actor pattern to confine shared mutable state to a coroutine. In this talk, actors are defined using a function whose parameters are ReceiveChannel (for inputs) or SendChannel (for outputs). Since those actors are defined as functions, how does they relate to classes ? Does anyone has concrete examples of how to structure a program with coroutines-based actors ?
    a
    p
    +2
    • 5
    • 7
  • d

    Dalinar

    01/30/2019, 4:49 AM
    what kind of exception handling is for
    future { }
    ?
    g
    • 2
    • 10
  • s

    sdeleuze

    01/30/2019, 1:47 PM
    Hey, I am working on Spring Coroutines support. WebFlux support (
    WebClient
    and the functional server API) is currently designed as extensions (https://github.com/spring-projects/spring-fu/tree/master/coroutines/webflux) since the API surface is big and only a small part is IO related. For methods returning
    Mono
    I am just using
    Publisher<T>.awaitSingle()
    or
    Publisher<T>.awaitFirstOrNull()
    , no problem there. For method where I need to create a
    Mono
    from a Coroutine this is less clear to me. I am currently doing
    GlobalScope.mono(Dispatchers.Unconfined) { ... }
    since with an extension I don't see how I should use constructs like
    fun CoroutineScope.doSometing() = mono { ... }
    . How I am supposed to handle that when using extensions? Also I am not really leveraging structured concurrency here, but since I am exposing a Reactive Streams core with Coroutines I am not sure yet if this is an issue or not. Support for Spring Data MongoDB (https://github.com/spring-projects/spring-fu/tree/master/coroutines/data-mongodb) and R2DBC (https://github.com/spring-projects/spring-fu/tree/master/coroutines/data-r2dbc) is based on dedicated Coroutines API since almost all the API is related to IO operation, I have used
    Co
    prefix like for
    CoDatabaseClient
    for example (https://github.com/spring-projects/spring-fu/blob/master/coroutines/data-r2dbc/src/main/kotlin/org/springframework/data/r2dbc/function/CoDatabaseClient.kt). Translating
    Flux
    support depends on https://github.com/Kotlin/kotlinx.coroutines/issues/254 so I have not started this part yet. I also still need to implement interop between Reactor and Coroutines context https://github.com/Kotlin/kotlinx.coroutines/issues/284 This is really the early stage, and I am not yet super familiar with Coroutines, so any feedback welcome.
    👍 2
    e
    g
    • 3
    • 4
  • a

    asad.awadia

    01/30/2019, 2:41 PM
    What does this function really mean? Is it launching a coroutine on each invocation?
    e
    • 2
    • 2
  • a

    asad.awadia

    01/30/2019, 2:41 PM
    And which dispatcher will it use?
    a
    • 2
    • 1
  • a

    ansman

    01/30/2019, 3:21 PM
    It’s too bad delegated properties can’t be
    suspend
    . It would be great to have a property that is backed by a
    Deferred
    s
    g
    • 3
    • 5
  • c

    curioustechizen

    01/30/2019, 3:34 PM
    I still haven't managed to verify that a suspending function is called in tests. I created a minimal project demonstrating the problem on GitHub - https://github.com/curioustechizen/kotlin-coroutines-test-issue If anyone has any ideas please let me know.
    a
    s
    • 3
    • 17
  • s

    streetsofboston

    01/30/2019, 3:45 PM
    @curioustechizen Try this
    class LogicTest {
        private lateinit var viewmodel: ViewModel
    
        private var repo: IRepository = mockk(relaxed = true)
    
        @BeforeEach
        fun setUp() {
            viewmodel = ViewModel(repo, Dispatchers.Unconfined)
    
        }
    
        @Test
        fun `when ViewModel init called then it calls repo init`() {
            viewmodel.init()
            verify { repo.init() }
        }
    
        @Test
        fun `when ViewModel getName called then it calls repo getName`()  {
            viewmodel.getName {  }
            runBlocking {
                coVerify { repo.getName() }
            }
        }
    }
    Note that I used MockK for the testing framework, not Mockito, but that should not matter. Update: Using Dispatchers.Unconfined is good enough for these tests. There is a known issues with Mockito verifying coroutines, but that should have been fixed in the latest version.
    a
    • 2
    • 5
  • j

    julioyg

    01/30/2019, 4:27 PM
    👋 is it ok if I open a subscription to a broadcastChannel and consume the items inside a coroutine and when I'm not interested on receiving items from the channel I just cancel the coroutine or do i need to explicitly close the channel?
    g
    a
    • 3
    • 11
  • a

    ansman

    01/30/2019, 6:43 PM
    Is a completed
    Job
    a large object? Should I remove old jobs or should they be cleaned up ASAP?
    l
    • 2
    • 1
  • d

    Dalinar

    01/30/2019, 7:00 PM
    I'm reading the docs here https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/ so
    isCompleted
    means cancelled or completed, `isCancelled`means cancelled, so to find out if it completed sucessfully there is no easier way than checking for
    isCompleted && !isCanclled
    ?
    a
    g
    • 3
    • 3
  • m

    Max Russek

    01/30/2019, 10:38 PM
    reference on azure functions: https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-concepts
    g
    • 2
    • 2
  • a

    asad.awadia

    01/31/2019, 2:45 AM
    Suspending functions are preferred over async/await - but how do you run two suspending function concurrently?
    g
    b
    g
    • 4
    • 11
  • a

    ahulyk

    01/31/2019, 2:39 PM
    Hi) I'm a bit confused about coroutines on Android: Example 1:
    launch(IO) {
                val result = repoRepository.getAllRepos()
                withContext(Main) {
                    textField.text = result
                }
            }
    Example 2:
    launch(Main) {
                val result = repoRepository.getAllRepos()
                withContext(Main) {
                    textField.text = result
                }
            }
    Question is why i'm not getting android.os.NetworkOnMainThreadException in second example?
    s
    l
    g
    • 4
    • 14
  • d

    Dias

    01/31/2019, 5:16 PM
    I am not sure if there is more concise way of doing that, maybe without need of wrapping failures into something else, something that uses coroutine exceptions handlers or
    select
    statement, etc
    h
    d
    • 3
    • 11
  • r

    rrva

    01/31/2019, 8:25 PM
    can I write a function, that could be used both in a coroutine context, and outside of a coroutine context, with a single signature, perhaps using an optional
    Continuation
    parameter?
    e
    • 2
    • 1
  • s

    streetsofboston

    02/01/2019, 4:25 AM
    @Sam Maybe this works, given a CoroutineScope:
    scope.coroutineContext[ContinuationInterceptor]
    s
    r
    • 3
    • 7
  • h

    hmgeorge

    02/01/2019, 5:08 AM
    Hello, tutorials on kotlin describe using suspendCoroutine or suspendCancelableCoroutine as the recommended way to deal with external libraries that provide a callback interface. However, most examples given seem to be for one shot results, e.g. make a network request and wait for the result. What would be the idiomatic way to handle interactions with external libraries that provide a listener interface. e.g. FileObserver on Android where we register to observe changes but we do not know when the callback will be issued. Is using Continuation<T> an acceptable method? E.g. https://gist.github.com/hmgeorge/1e5ee34265d5154e05251c1287843515 . or is using a Channel preferred?
    s
    • 2
    • 4
  • d

    Dalinar

    02/01/2019, 5:55 AM
    I saw some headline while searching about coroutines on one of the the Jetbrains guy's blogs - and only took in the headline that sounded something like "GlobalScope shouldn't be used" - but I didn't really know what a GlobalScope was, now I see I need to read up on it. can't find the blog anymore - so I mean it probably just meant that it shouldn't be used in a specific circumstance but I didn't read the page more than just glimpse the title
    e
    • 2
    • 2
  • p

    pajatopmr

    02/01/2019, 8:39 AM
    “Is it secret Frodo? Is it SAFE?” So I have this piece of code (first serious coroutine hacking I’ve done) where I have a map associating names with lists of data. The main thread will allow clients to access the lists while a daily background thread will update the data. Main thread is read-only, Background thread is write-only. I think, from an app perspective, that this code is safe even if not predictable. So am I correct?
    o
    m
    e
    • 4
    • 11
  • a

    ahmad

    02/01/2019, 12:08 PM
    Hello guys, I was exploring kotlin coroutines source code and I found a lot of unused imports. Is this intentionally? or it would be OK if I submit a PR to remove them?
    e
    • 2
    • 3
  • k

    koufa

    02/01/2019, 3:46 PM
    Hey I have a question:
    fun main() = runBlocking {
        try {
            cScope()
        } catch (error: Throwable) {
            println(error)
        }
    }
    
    suspend fun cScope() = coroutineScope {
        val def = async { failure() }
        try {
            def.await()
        } catch (error: Throwable) {
            println(error)
        }
    }
    Why is it only possible to
    catch
    the error when wrapping
    cScope()
    and not
    def.await()
    ?
    a
    g
    • 3
    • 12
  • g

    gergo

    02/01/2019, 5:39 PM
    👋 hello guys, im a newbie with coroutines. Im trying to test my ViewModel which simplified looks like the attached code. My issue is that sometimes the tests succeeds but sometimes fails. I can't figure out what am I doing wrong. Could someone help me with that? (the repeat is there to see if it works "all the time")
    -.kt
    w
    g
    s
    • 4
    • 14
  • p

    Paul Woitaschek

    02/02/2019, 9:22 PM
    Currently I have a
    suspend fun <http://CoroutineContext.xyz|CoroutineContext.xyz>()
    and I perform a check and then call
    coroutineContext.cancel()
    and then throw a
    CancellationException
    .
    a
    • 2
    • 9
Powered by Linen
Title
p

Paul Woitaschek

02/02/2019, 9:22 PM
Currently I have a
suspend fun <http://CoroutineContext.xyz|CoroutineContext.xyz>()
and I perform a check and then call
coroutineContext.cancel()
and then throw a
CancellationException
.
a

Allan Wang

02/02/2019, 9:22 PM
What do you mean by check? Also note that whenever you switch contexts (withContext), the runnables will automatically not be called if the coroutine is cancelled
p

Paul Woitaschek

02/02/2019, 9:23 PM
https://github.com/PaulWoitaschek/Voice/blob/81e5160ac67ceea11d40bfff72f90f6856cfb4a4/app/src/main/java/de/ph1b/audiobook/features/BookAdder.kt#L195-L198
a

Allan Wang

02/02/2019, 9:23 PM
If you also just want to insert breakpoints during an execution, you can use
yield()
p

Paul Woitaschek

02/02/2019, 9:23 PM
So you suggest to just throw the exception?
a

Allan Wang

02/02/2019, 9:23 PM
Throwing alone should work
You also might not want to use both
suspend
and
CoroutineScope
extensions in one method. Suspending functions are long executions whereas coroutine scope functions launch and return quickly
p

Paul Woitaschek

02/02/2019, 9:26 PM
It was only to cancel the job
Thanks!
https://github.com/PaulWoitaschek/Voice/commit/ef901ae52642fe36de10507451931f8922ee1545
View count: 2