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

    lukaswelte

    10/15/2018, 6:45 AM
    I’m trying to understand
    Continuation
    in detail. Can someone recommend some good resources on the topic?
    g
    • 2
    • 3
  • o

    otakusenpai

    10/15/2018, 12:45 PM
    Hey guys, So I have a server class which contains a map of strings to bots, and theres this function in the server class called runBots() which run all the bots. This is what I have for a implementation:
    fun runBots() = runBlocking {
            try {
                bots.forEach {
                    val one = launch { it.value.setConnection(); }
                    one.join()
                    delay(3000L)
                    if(it.value.running) {
                        it.value.Connect()
                    }
                }
            } catch(e: Throwable) {
                bots.forEach { if(!it.value.running) it.value.Connect() }
            }
        }
    "bots" here is the map of strings to bots. Each bot has a Connect() function(a async function) which runs the all the bot's main loop. The problem is that the bot doesnt run, after the server class calls it's runBots function.
    Initialised
    Connnected: true
    Defined bot
    Added bot
    [main] Connecting....
    [main] Sending nick...
    Sending nick: NICK Kraken3635
    
    [main] Sending user...
    Sending user: USER Nani 0 * :Nani
    
    [main] Connected!
    [DefaultDispatcher-worker-1] I'm now in Connect!
    [DefaultDispatcher-worker-1] Entering loop...
    e
    g
    • 3
    • 32
  • e

    enleur

    10/15/2018, 1:32 PM
    I like the convention about
    CoroutineScope
    extensions, but I think it should be also in docs
    e
    • 2
    • 1
  • g

    gildor

    10/15/2018, 1:51 PM
    I don't see any safely issues with the first. But you cannot use first approach in some cases. For example you cannot use it for Android Fragments when Job can be recreated
    l
    k
    • 3
    • 6
  • i

    itnoles

    10/15/2018, 2:53 PM
    I am getting <undefinedtype> from suspend block when I looked into the ByteCode Viewer. https://gist.github.com/iNoles/6df55f2244b02f781a480a5a2b978544
    i
    • 2
    • 1
  • o

    otakusenpai

    10/15/2018, 4:30 PM
    suspend fun addEvent(value: MsgType): Event {
        val eventChannel = Channel<Event>()
        var event: Event? = null
    
        log("joining", logMessages)
        if (value == MsgType.ping) {
            log("ping", logMessages)
            eventChannel.send(PingEvent(value) as Event)
        }
        else if (value == MsgType.join) {
            log("join", logMessages)
            eventChannel.send(JoinEvent(value) as Event)
        }
        else if (value == MsgType.normal) {
            log("normal", logMessages)
            eventChannel.send(NormalEvent(value) as Event)
        }
        else if (value == MsgType.privmsg) {
            log("privmsg", logMessages)
            eventChannel.send(PrivMsgEvent(value) as Event)
        }
        else if (value == MsgType.mode) {
            log("mode", logMessages)
            eventChannel.send(ModeEvent(value) as Event)
        }
        else if (value == MsgType.notice) {
            log("notice", logMessages)
            eventChannel.send(NoticeEvent(value) as Event)
        }
        else if (value == MsgType.special) {
            log("special", logMessages)
            eventChannel.send(SpecialEvent(value) as Event)
        }
        else if (value == MsgType.namelist) {
            log("namelist", logMessages)
            eventChannel.send(NameListEvent(value) as Event)
        }
        else if (value == MsgType.topic) {
            log("topic", logMessages)
            eventChannel.send(TopicEvent(value) as Event)
        }
        else if (value == MsgType.topic_whotime) {
            log("whotime", logMessages)
            eventChannel.send(TopicWhoTimeEvent(value) as Event)
        }
        else if (value == MsgType.quit) {
            log("quit", logMessages)
            eventChannel.send(QuitEvent(value) as Event)
        }
        else if (value == MsgType.who) {
            log("who", logMessages)
            eventChannel.send(WhoEvent(value) as Event)
        }
        else if (value == MsgType.end_of_who) {
            log("end of who", logMessages)
            eventChannel.send(EndOfWhoEvent(value) as Event)
        }
    
        log("receiving", logMessages)
        event = eventChannel.receive()
    
        log("received", logMessages)
        if(event == null)
            throw AghoraException("Error: In addEvent(value: MsgType): Event in " +
            " com.github.otakusenpai.aghora.irc: No implementation of MsgType ${value.toString()}")
    
        log("returning", logMessages)
        return event
    }
    Can anyone explain why this code isnt returning the value from the Channel ?
    e
    c
    g
    • 4
    • 8
  • c

    claudiug

    10/15/2018, 6:29 PM
    I was thinking to parse some pdf's and for each file to create a new coroutine, but after that I've stop
    e
    • 2
    • 4
  • c

    claudiug

    10/15/2018, 6:30 PM
    I will be very happy for some links, any links 🙂
    e
    d
    • 3
    • 2
  • r

    Ruckus

    10/15/2018, 7:37 PM
    Is there a standard way to skip a select clause for a closed channel?
    onReceiveOrNull
    doesn't really work if I have multiple channels and want the rest to continue if any of them close (as
    select
    is biased to the first).
    e
    v
    • 3
    • 6
  • d

    digitalsanctum

    10/15/2018, 7:55 PM
    Also wondering if there's new versions of examples here: https://github.com/Kotlin/kotlin-coroutines/tree/master/examples which seem to be 2 years old now?
    e
    e
    g
    • 4
    • 6
  • j

    JoeHegarty

    10/15/2018, 9:08 PM
    Is there a way to say "give me the coroutine context if I am in a coroutine"? I basically want/need a way to detect if I am running in a coroutine and to grab the context, even in a non suspending method. It that possible?
    d
    g
    +2
    • 5
    • 69
  • d

    digitalsanctum

    10/15/2018, 10:03 PM
    What's the best way to track metrics of the rate at which items are flowing through channels? I could do it at each consumer/receiver but if you have more than one then you have to aggregate somehow
    d
    • 2
    • 1
  • d

    dave08

    10/16/2018, 3:15 AM
    What about using
    class MainPresenter : CoroutineScope by CoroutineScope(Dispatchers.Main)
    to get rid of a bit of boilerplate, just missing an easy way to access its Job to cancel it on the end of its lifecycle...?
    g
    • 2
    • 4
  • o

    oshai

    10/16/2018, 7:12 AM
    Is it possible to know how many messages are waiting for an actor to process?
    • 1
    • 1
  • r

    robin

    10/16/2018, 3:01 PM
    So I'm fooling around with sleepsort to try how I can make channels and sequences interact:
    suspend fun main(args: Array<String>) = runBlocking {
    
        val unsorted = generateSequence { Random.nextInt() }.take(200)
        val sortedChannel = Channel<Int>()
        val sorted = sequence { for (msg in sortedChannel) yield(msg) }
        unsorted.map { async { delay(it * 10L); sortedChannel.send(it) } }
        sorted.forEach(::println)
    }
    But I'm getting an error about restricted suspending functions where I'm iterating over the channel. Can anyone tell me what that's about?
    z
    • 2
    • 17
  • r

    Robert Menke

    10/16/2018, 3:32 PM
    Hey guys, I’m trying to understand `Job`’s
    cancel
    method. I’m working on creating a class that implements
    CoroutineScope
    and I’m following the example here https://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-core/test/guide/example-context-10.kt. I would expect that
    job.cancel()
    would return true in this case since the invocation of cancel is what cancels the job, however, when I print the result of
    job.cancel()
    I get false.
    fun destroy() {
         val temp = job.cancel()
         print(temp.toString()) //prints "false" even though I would expect it to print "true"
    }
    Am I misunderstanding cancel?
    e
    d
    • 3
    • 4
  • z

    Zach Klippenstein (he/him) [MOD]

    10/16/2018, 3:57 PM
    Once the 1.0 version of the coroutines library is released, would it be possible to include it as a dependency from play.kotlinlang.org? It would be really handy to be able to share code sketches to demonstrate coroutines usage.
    v
    • 2
    • 2
  • d

    Dias

    10/16/2018, 5:06 PM
    hey, qq on exception handling. How do I make coroutine stop if a child coroutine throws an exception:
    launch {
                launch {
                    throw RuntimeException()
                }
                while (true) {
                    println("123123")
                }
            }
    I want parent launch to exit with an exception, but not sure how to
    d
    r
    +3
    • 6
    • 51
  • a

    Allan Wang

    10/16/2018, 6:04 PM
    I just watched the coroutine talk about creating a service that takes in locations, fetches content for new locations, and then reuses contents if a location has already been fetched:

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

    Over there, it looks like if any content fetching fails, the entire service is cancelled. How do we make it so that failing a content fetch will only cancel requests based on that particular location? The docs look like any exception beyond
    CancellationException
    will cancel the parent no matter what, so do we have to wrap our code in a try catch? To be more specific, this is the problem I want to solve: I have a method that takes in an id and returns an auth object I have other methods that will take in an auth object and then output something else I want to create a running stream for the duration of my lifecycle that will take in ids and actions. If an auth does not exist (say in a map), I want to fetch it. Once an auth is fetched, I want to run any pending actions on that auth. If an auth is being fetched and another request is made requiring that auth, it should wait for the previous fetch rather than getting a new auth itself. This pattern is already shown in the talk using
    Map<T, List<K>>
    . If the auth fetch fails, I want to cancel any pending actions. If an action fails, or anything else outside of this scope, I want the
    CoroutineScope
    to stay alive, until it is cancelled by the lifecycle.
    e
    • 2
    • 1
  • s

    Slackbot

    10/16/2018, 8:35 PM
    This message was deleted.
    e
    r
    • 3
    • 3
  • g

    groostav

    10/17/2018, 12:12 AM
    Is simply assuming its OK to dispatch things on the common pool an OK practice? What about the default executor?
    g
    e
    • 3
    • 2
  • g

    groostav

    10/17/2018, 12:12 AM
    the typical java answer would be to expose `ExecutorService`'s at API entry points, but that seems like a clooge, at so should I simply expose `CoroutineDispatcher`s in the same vein? Should I fetch them off the callers
    scope
    ?
    g
    • 2
    • 1
  • m

    myanmarking

    10/17/2018, 10:27 AM
    java.lang.IllegalStateException: Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher
    release builds only
    e
    • 2
    • 2
  • j

    Jonathan

    10/17/2018, 11:52 AM
    Do you know where I could found a bigger version of the suspend logo? (for a presentation)
    h
    l
    • 3
    • 7
  • v

    voddan

    10/17/2018, 12:19 PM
    ❓ What is supposed to happen if
    async {}
    block throws an exception, but the result is never used? I get different behaviour in playground and InteliJ https://pl.kotl.in/rkOAdiNiQ
    suspend fun main() {
        coroutineScope {
            val x = async { null!! }
        }
        
        println("end")
    }
    g
    d
    • 3
    • 10
  • a

    antoin_m

    10/17/2018, 1:45 PM
    Hey 🙂 Quick stupid question. When you’re in a coroutine and call a blocking java function (like a guava future’s get method) does it block the whole thread? I’d say yes but then how do you handle libraries that use that kind of future internally?
    l
    d
    • 3
    • 2
  • t

    tw

    10/17/2018, 1:53 PM
    I had a similar question I’ve been meaning to ask - I’m working with a third party library that has a blocking call - it’s non-cpu intensive (just a really basic subscription) - but I am unsure of the best way to allow many of these subscriptions to run at the same time with co-routines
    e
    d
    • 3
    • 3
  • a

    antoin_m

    10/17/2018, 1:59 PM
    Thanks @louiscad, so would it be a good solution to wrap the calls in what @enleur suggested here -> https://kotlinlang.slack.com/archives/C1CFAFJSK/p1539784566000100?thread_ts=1539784399.000100&amp;cid=C1CFAFJSK ?
    l
    j
    • 3
    • 6
  • s

    spierce7

    10/17/2018, 3:38 PM
    Does anyone have a link to the code from Roman's recent talk on coroutines?
    c
    j
    • 3
    • 3
  • e

    enleur

    10/17/2018, 9:00 PM
    why do you mix rx and coroutines?
    p
    v
    • 3
    • 5
Powered by Linen
Title
e

enleur

10/17/2018, 9:00 PM
why do you mix rx and coroutines?
p

Paul Woitaschek

10/17/2018, 9:09 PM
Legacy
e

enleur

10/17/2018, 9:10 PM
well, check https://github.com/Kotlin/kotlinx.coroutines/blob/master/reactive/kotlinx-coroutines-reactive/README.md to convert reactive streams to coroutine objects
p

Paul Woitaschek

10/17/2018, 9:10 PM
I do exactly that?
e

enleur

10/17/2018, 9:16 PM
yeah sorry
v

Vsevolod Tolstopyatov [JB]

10/18/2018, 8:02 AM
Because they do not exclude each other (yet). We still has no cold streams
View count: 4