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

    spand

    10/10/2018, 9:03 AM
    Say I have a
    val scope = GlobalScope + Job()
    that is no longer active. If I call
    scope.launch
    the new coroutine will never get a chance to execute but caller of
    launch
    is oblivious to this. Would it not make more sense have a fail fast behaviour akin to
    Executor.execute
    that throws
    RejectedExecutionException
    in a similar situation ?
    e
    g
    • 3
    • 21
  • j

    Jonathan

    10/10/2018, 9:17 AM
    I tried to achieve "well-designed" actor system. But in my experimentations I found very difficult to compose actors without using the ask & wait anti-pattern. It is possible, but it quickly leads overcomplicated code IMHO. Do you have good resources where I could learn how to nicely compose actors without ask & wait?
    e
    d
    e
    • 4
    • 35
  • t

    tiwiz

    10/10/2018, 10:04 AM
    Ehy y'all! I have a problem with testing with the new Coroutines. The problem is that I have a very long sync operation and I want to test the
    runBlocking
    behaviour happens even with a possible delay. In the following gist (https://gist.github.com/tiwiz/b85c72fb77148e6cc12aa378b762e94b) there is the code (the
    delay
    is only to test if the test waits or not). So far, we couldn't have it to wait, so we must be doing something wrong... does anyone have a clue about it?
    j
    g
    f
    • 4
    • 34
  • r

    rocketraman

    10/10/2018, 12:54 PM
    How best to call suspend functions from
    Sequence.map
    and
    flatMap
    ? These operations on
    Sequence
    are not inlined, unlike
    List
    , so you get the error
    Suspension functions can only be called within coroutine body
    . I don't want to use
    runBlocking
    inside the lambda.
    j
    d
    • 3
    • 6
  • p

    poohbar

    10/10/2018, 4:21 PM
    fun <A, B> Sequence<A>.pmap(f: suspend (A) -> B): Sequence<B> = runBlocking {
        map { async(Dispatchers.Default) { f(it) } }.map { it.await() }
    }
    how come this says
    Suspension function can be called only within couroutine body
    on the
    it.await()
    call?
    z
    d
    • 3
    • 3
  • s

    serebit

    10/10/2018, 5:52 PM
    are coroutines going to be merged into the standard library (kotlin-stdlib) for the 1.3 release, or will they remain a separate artifact?
    e
    t
    • 3
    • 13
  • d

    digitalsanctum

    10/10/2018, 6:56 PM
    I'm getting started using coroutines and attempting to do a fan out with single producer and multiple consumers. if executing via main, what's the best way to signal the main thread when consumers are done consuming without using
    delay
    ?
    e
    • 2
    • 4
  • o

    otakusenpai

    10/10/2018, 7:27 PM
    Well I want the docs for ByteReadChannel and ByteWriteChannel But i can't find the io package here https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/
    r
    d
    e
    • 4
    • 10
  • s

    spand

    10/11/2018, 6:13 AM
    Is this correct and the most concise way of having cleanup in the implement CoroutineScope pattern?
    class Activity : CoroutineScope {
        var job = Job()
        override val coroutineContext: CoroutineContext
            get() = Dispatchers.Default + job
    
        init {
            val workJob = launch(start = CoroutineStart.LAZY) {
                // Doing stuff
                delay(5000)
            }
            launch(start = CoroutineStart.ATOMIC) {
                try {
                    workJob.join()
                } finally {
                    println("Cleaning up")
                }
            }
        }
    
        fun destroy() {
            job.cancel()
        }
    }
    g
    d
    k
    • 4
    • 29
  • d

    David W

    10/11/2018, 3:36 PM
    Any recommendations on how to unit test an
    actor
    ? Basically I have a redux-ish pipeline where each input may result in 0+ state changes. Not sure how to tell when my pipeline is "inactive".
    greatly_simplified_pipeline.kt
    j
    • 2
    • 38
  • a

    acando86

    10/11/2018, 5:07 PM
    I have a list of ids and for each single id i wanna perform a network request to fetch more data about that id, and return the list of "hydrated" ids.. this is a pretty standard usecase, so far so good. I have a suspend function to fetch the data for a single id, I wanna parallelise the network requests, and it's important for me that the final list is in the same order of the original list (aka, kind of
    concatMap
    of Rx). Is
    awaitAll
    order-preserving on lists? if not, what's the best way to be non-blocking on the map while keeping the order of the list?
    e
    e
    • 3
    • 5
  • r

    Ruckus

    10/11/2018, 8:45 PM
    Does
    Mutex.tryLock()
    always return true? Or does it just not work like
    ReentrantLock
    ?
    e
    z
    +2
    • 5
    • 11
  • s

    Slackbot

    10/12/2018, 5:15 AM
    This message was deleted.
    👍 1
    g
    • 2
    • 1
  • j

    Jan

    10/12/2018, 9:13 AM
    hi guys, i'd like to learn more about coroutines, can someone point me some good sources that explain error handling well?
    d
    e
    • 3
    • 3
  • m

    mayojava

    10/12/2018, 9:51 AM
    while trying to explain the difference
    runBlocking
    and
    coroutineScope
    in the coroutine docs, it says
    coroutineScope
    does not block the current thread while waiting for all its children to complete. Then an example was given that shows otherwise.
    coroutineScope
    actually blocks the thread that
    runBlocking
    was invoked from while waiting for its children to complete. Have I understood this the wrong way?
    e
    j
    • 3
    • 2
  • m

    mayojava

    10/12/2018, 9:52 AM
    This is the example:
    fun main(args: Array<String>) = runBlocking { // this: CoroutineScope
        launch { 
            delay(200L)
            println("Task from runBlocking")
        }
        
        coroutineScope { // Creates a new coroutine scope
            launch {
                delay(500L) 
                println("Task from nested launch")
            }
        
            delay(100L)
            println("Task from coroutine scope") // This line will be printed before nested launch
        }
        
        println("Coroutine scope is over") // This line is not printed until nested launch completes
    }
    e
    d
    • 3
    • 4
  • e

    enleur

    10/12/2018, 10:31 AM
    it is funny to watch how in Golang they are trying to solve problems that was solved in kotlin by design https://posener.github.io/goroutine-scoped-context/ (coroutineContext) https://github.com/golang/go/issues/27982 (job cancel) in my production code I found myself using channels only twice and never had to use selects. at the same time in Golang.. well, you don’t have any deferred/promise from the box and have to do workarounds with channels, selects, sync.Wait and if you want to do cancel or timeout you will end up with tons of boilerplate code
    e
    • 2
    • 1
  • m

    marcinmoskala

    10/12/2018, 10:36 AM
    Is there any explanation?
    e
    i
    • 3
    • 10
  • v

    Vsevolod Tolstopyatov [JB]

    10/12/2018, 12:21 PM
    “Android Suspenders by Chris Banes” talk from KotlinConf'18 is now available on youtube:

    https://www.youtube.com/watch?v=P7ov_r1JZ1g▾

    Even if you are not an Android developer, this talk has a good explanation of coroutines mental model,
    CoroutineScope
    rationale and
    kotlinx.coroutines
    API overview in 30 minutes.
    👍 17
    ❤️ 3
    k
    v
    e
    • 4
    • 5
  • l

    lukaswelte

    10/12/2018, 1:13 PM
    Is there a function on
    CoroutineScope
    which is
    onError
    ? So in case any of the coroutines in the scope are cancelled or failing it will not cancel the parent scope routines, but instead invoke the error handler. Or is
    try-catch
    around the
    coroutineScope {}
    currently the only way?
    e
    d
    k
    • 4
    • 14
  • m

    muralimohan962

    10/12/2018, 2:21 PM
    Does the coroutineScope {} block the runBlocking coroutine code?
    e
    • 2
    • 2
  • l

    lukaswelte

    10/12/2018, 3:16 PM
    The “coroutines are lightweight” example will produce a OutOfMemory Exception in the kotlin playground. Is there something special about the playground or did something change in regard to how coroutines https://pl.kotl.in/SysF9E09m
    import kotlinx.coroutines.*
        
    fun main() = runBlocking {
        repeat(100_000) { // launch a lot of coroutines
            launch {
                delay(1000L)
                print(".")
            }
        }
    }
    🤣 3
    e
    • 2
    • 2
  • s

    spierce7

    10/12/2018, 3:47 PM
    Something I haven't quite figured out that has been bothering me about the
    RendezvousChannel
    . The
    RendezvousChannel
    seems like a
    PublishSubject
    from RX, but the documentation says something that worries me:
    An element is transferred from sender to receiver only when send and receive invocations meet in time
    So I understand that before I start listening to the
    Channel
    , all events emitted to it won't be received. Is it possible though that if I'm already listening to events on the
    Channel
    that I'll miss any?
    v
    d
    • 3
    • 8
  • r

    Ruckus

    10/12/2018, 4:54 PM
    If you use a different scope for
    launch
    (like
    GlobalScope
    ) your code will work without
    yield
    .
    m
    g
    • 3
    • 4
  • e

    enleur

    10/13/2018, 7:46 PM
    suspend fun whatever() = coroutineScope{
        while(isActive){ ... }
    }
    g
    • 2
    • 1
  • p

    Paul Woitaschek

    10/13/2018, 7:59 PM
    Thanks, that works (both)
    g
    • 2
    • 2
  • t

    TwoClocks

    10/13/2018, 9:21 PM
    How do I get a "handle" to a provuce<T> if the stuff I want to produce can't be done inside the {}? Or another way of asking : How do I create a one-way channel?
    e
    • 2
    • 1
  • a

    Allan Wang

    10/14/2018, 12:13 AM
    I’m still at the stage where I’m reading about coroutines rather than using it extensively, but I have a few more questions: When it comes to writing suspended functions, is there anything we should look out for in terms of potential memory leaks? If I compare Android coroutines with anko, anko tends to wrap the receiver with a weakreference, so that you can retrieve it again during your call. It’s written as type
    (T) -> Unit
    vs
    T.() -> Unit
    , which strikes me as a bit odd as anyone can use the original variable and forget about trying to get it from the weak reference. With coroutines, I don’t think weak references are used correct? Would it stand that so long as we make the coroutine scope agree to our lifecycle, we don’t have to worry about leaking variables beyond what we would normally consider when writing synchronous code? More specifically to Android, is there a general practice for writing suspended functions dealing with
    Context
    in a utility class where context would be passed through as an argument? Is it fine that we keep a global hashmap of deferred results if the scope cancels the job when appropriate?
    g
    • 2
    • 10
  • o

    oshai

    10/14/2018, 7:37 AM
    Hi, I am working on an ObjectPool that is using coroutines Actor and I will really be thankful for any code review feedback. It is not done yet but the code is here: https://bit.ly/2CI5bQZ and there are tests here https://bit.ly/2RLX4al Thanks in advance
    • 1
    • 2
  • e

    egorand

    10/14/2018, 6:22 PM
    I’ve got the following problem: here’s an interface called `Source`:
    interface Source : Closeable {
      @Throws(IOException::class)
      fun read(sink: Buffer, byteCount: Long): Long
    }
    I’m declaring
    SuspendingSource
    like this:
    interface SuspendingSource : Source {
      @Throws(IOException::class)
      override suspend fun read(sink: Buffer, byteCount: Long): Long
    }
    which doesn’t compile because of
    Conflicting overloads
    . Is it forbidden to override non-suspend functions with suspend ones?
    d
    b
    • 3
    • 3
Powered by Linen
Title
e

egorand

10/14/2018, 6:22 PM
I’ve got the following problem: here’s an interface called `Source`:
interface Source : Closeable {
  @Throws(IOException::class)
  fun read(sink: Buffer, byteCount: Long): Long
}
I’m declaring
SuspendingSource
like this:
interface SuspendingSource : Source {
  @Throws(IOException::class)
  override suspend fun read(sink: Buffer, byteCount: Long): Long
}
which doesn’t compile because of
Conflicting overloads
. Is it forbidden to override non-suspend functions with suspend ones?
d

Dominaezzz

10/14/2018, 6:43 PM
Yes, it is forbidden. Since the anyone calling
Source.read
doesn't not know to suspend.
e

egorand

10/14/2018, 6:47 PM
Ah, makes sense
b

Burkhard

10/14/2018, 11:42 PM
It’s also quite intuitive if you look at the generated bytecode of a suspend function. They work by passing a hidden extra argument which tells the function where to resume.
View count: 2