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

    geekasm

    09/28/2017, 9:10 AM
    but its in scala
    d
    6 replies · 2 participants
  • b

    bj0

    09/29/2017, 11:49 PM
    I was just thinking it would be nice if you were only working in a single context (like UI, or a single thread), that it would be nice to make the default "keep using current context"
    e
    d
    7 replies · 3 participants
  • e

    elizarov

    10/01/2017, 6:54 AM
    @mkobit: it works, but it is a kludgy way to do it. You should just add
    kotlinx-coroutines-jdk8
    module to your deps and use
    process.onExit().await()
    .
    m
    1 reply · 2 participants
  • d

    dave08

    10/02/2017, 8:05 AM
    Maybe a class that implements Handler and has a fun that returns a ProducerJob which sends anything the handler receives?
    1 reply · 1 participant
  • d

    dave08

    10/03/2017, 1:22 PM
    I'm also wondering how I could send the same message to multiple channels (not fanOut in the docs..) from one
    produce { }
    function?
    o
    3 replies · 2 participants
  • m

    matej

    10/05/2017, 5:06 PM
    to bridge the gap with a legacy system
    e
    23 replies · 2 participants
  • j

    jw

    10/06/2017, 1:15 PM
    Even inside
    suspendCoroutine
    ? That means that block finished executing before the result is returned?
    e
    2 replies · 2 participants
  • s

    sdeleuze

    10/06/2017, 1:19 PM
    @elizarov I am starting to work on Reactor and Spring support for co-routines, as a beginning I have submitted this PR (https://github.com/Kotlin/kotlinx.coroutines/pull/141).
    reactor-core
    3.1 (included in
    Bismuth
    ) is the real GA since the one shipped with Spring Framework 5 for which we garantee API stability, so no need to support the old one.
    e
    1 reply · 2 participants
  • k

    kenkyee

    10/07/2017, 11:21 AM
    Yep... I'd guess the server has to be launched first... Looks like it's done at the end. Actually brings up an interesting question if you launch a bunch of coroutines and join later... Is there any way to get them to run sequentially or would you have to launch one from within another to do it. Though I can't think of a reason to ever need to do this 😀
    n
    1 reply · 2 participants
  • e

    elizarov

    10/07/2017, 8:44 PM
    📣 📣 📣
    kotlinx.coroutines
    version
    0.19.1
    is released. It is a patch that fixes a serious race in
    ArrayBroadcastChannel
    (it was there since introduction) and updates
    kotlinx.coroutines.reactor
    to leverage Bismuth release train. Full list of changes in here: https://github.com/Kotlin/kotlinx.coroutines/releases
    👏 4
    s
    1 reply · 2 participants
  • r

    raulraja

    10/07/2017, 10:46 PM
    @elizarov We are using coroutines to achieve monad bind syntax in Kategory generalized to all monads and it looks like this for example with Option.
    Option.monad().binding {
      val a = Option(1).bind()
      val b = Option(a + 1).bind()
      yields(b)
    }
    //Option(2)
    binding
    is a Continuation and
    bind
    is implemented as a
    COROUTINE_SUSPENDED
    function that unwinds
    flatMap
    calls until the entire binding is completed as shown here https://github.com/kategory/kategory/blob/master/kategory-core/src/main/kotlin/kategory/typeclasses/MonadContinuations.kt#L53-L61 For this to work we are resorting to a dirty hack which is making the private
    label
    and
    completion
    properties visible so we can mutate them accordingly. https://github.com/kategory/kategory/blob/master/kategory-core/src/main/kotlin/kategory/typeclasses/ContinuationUtils.kt Do you know if there is a better way of doing this? Thanks in advance for any pointers in the right direction 🙂
    e
    p
    20 replies · 3 participants
  • e

    elizarov

    10/08/2017, 6:48 AM
    @voddan 0.19.1 is in central
    👍 2
    v
    4 replies · 2 participants
  • o

    okkero

    10/08/2017, 12:34 PM
    it doesn't seem to match 0.19.1
    e
    1 reply · 2 participants
  • l

    langara

    10/08/2017, 2:35 PM
    Check out my new article about simple android app using coroutines: https://blog.elpassion.com/create-a-clean-code-app-with-kotlin-coroutines-and-android-architecture-components-f533b04b5431
    👍 4
    e
    1 reply · 2 participants
  • d

    Dmytro Danylyk

    10/09/2017, 6:14 AM
    https://medium.com/@dmytrodanylyk/android-coroutine-recipes-33467a4302e9
    g
    19 replies · 2 participants
  • j

    jkbbwr

    10/10/2017, 12:37 PM
    >> put multiple containers into one JVM instance, which allows to deploy many small Java applications in large scale, across data centers,
    use coroutines (from Da Vinci Machine project) to reduce context switches, implement quick Java warmup to obviate the need for “warming-up” occurred in initialization phase of the eCommerce applications
    e
    2 replies · 2 participants
  • e

    elizarov

    10/10/2017, 1:44 PM
    @rrva Conceptually, it is the same. Just a different name for the same concept. https://en.wikipedia.org/wiki/Fiber_(computer_science)
    r
    6 replies · 2 participants
  • d

    detouched

    10/13/2017, 5:09 AM
    Hi there, may I have a hopefully quick review please? I'm trying to implement a version of
    select
    that waits for the first successful result (opposed to the existing one that waits for the first completed clause, no matter exceptionally or not). First of all, am I reinventing the wheel? If not, here's what I ended up with – does it make sense? Any issues you can see here?
    private suspend fun <R, D : Deferred<R>> selectFirstSuccessful(deferredList: List<D>,
                                                                   failedDeferredList: List<D>): Triple<R?, List<D>, List<D>> =
            if (deferredList.isEmpty()) {
                Triple(null, deferredList, failedDeferredList)
            } else {
                try {
                    select<Triple<R?, List<D>, List<D>>> {
                        deferredList.forEach { deferred ->
                            deferred.onAwait { result -> Triple(result, deferredList - deferred, failedDeferredList) }
                        }
                    }
                } catch (e: Exception) {
                    val completedExceptionally = deferredList.filter { it.isCompletedExceptionally }
                    val notCompletedExceptionally = deferredList - completedExceptionally
                    selectFirstSuccessful(notCompletedExceptionally, completedExceptionally + failedDeferredList)
                }
            }
    Full code with usage example is here: https://gist.github.com/detouched/73f366cb730ece629b9141dea96d3a98
    v
    1 reply · 2 participants
  • d

    detouched

    10/13/2017, 12:56 PM
    @elizarov How will that help with awaiting for the first actually successful coroutine? Never failing one will still have to return something — some "empty" value I guess. Or do you mean keeping this approach but simplifying it by calling self in
    onAwait
    instead of
    catch
    in the case
    result
    is "empty"? I'm actually interested in the failures in some cases, so I need to somehow pass them through anyway to inspect them later.
    e
    1 reply · 2 participants
  • e

    elizarov

    10/16/2017, 7:42 PM
    Coroutines are good if your work that you have to do on each element is asynchronous (needs to wait for something, like network call). If it is all just CPU-bound, you’d be better off using Java parallel streams — they are specifically optimized for parallelization of CPU-bound computations.
    👍 6
    n
    6 replies · 2 participants
  • e

    elizarov

    10/18/2017, 1:06 PM
    @dave08 I’m somewhat lost at what problem you are trying to solve and what is the solution your are trying to apply. I don’t see how sending over channel inside a mutex should do anything. Can you post somewhere (like a gist) a larger example (a unit test, maybe?) that demonstrates what you are trying to do and what does not work?
    u
    d
    14 replies · 3 participants
  • u

    uli

    10/18/2017, 4:19 PM
    like this in the example above:
    counter.send(GetCounter(response))
        println("Counter = ${response.await()}")
        counter.close() // shutdown the actor
    }
    d
    u
    32 replies · 3 participants
  • e

    elizarov

    10/19/2017, 11:00 AM
    asyncio
    analogue is a work in progress still. We’ll have some separate guide for it when it is released
    s
    4 replies · 2 participants
  • d

    dave08

    10/19/2017, 3:07 PM
    But a with a buffer, offer does it when it can, or still returns false?
    c
    1 reply · 2 participants
  • f

    functionaldude

    10/19/2017, 5:54 PM
    Hi! I recently encountered a strange behavior. I have a
    HashMap
    which is only accessed and modified in a single coroutine context:
    val pushNotificationGeneratorThread = newSingleThreadContext(name = "Push Notification Generator Thread")
    suspend fun clear() = run(pushNotificationDispatcherThread) {
        lastNotificationDates.clear()
      }
    suspend fun put(key: String, value: Any) = run(pushNotificationDispatcherThread) {
        lastNotificationDates.put(key, value)
      }
    However sometimes I still get a
    ConcurrentModificationException
    . In my understanding this should be threadsafe.
    b
    12 replies · 2 participants
  • e

    eygraber

    10/20/2017, 6:41 PM
    Hello all, I've been reading the docs and the KEEP, but I'm not sure I fully understand what coroutines offer. The example I've been keeping in my head is a server that responds to all requests with a randomly selected quote that it retrieves from a remote service. The call to that service and the response sent back to the client is done on a separate thread than the one the request comes in on. Using vanilla executors we would pass a
    Runnable
    that makes the network call and writes the response. Using Rx it would look something like:
    quoteService
        .getQuote()
        .flatMap(response::write)
        .subscribeOn(<http://Schedulers.io|Schedulers.io>())
        .subscribeBy(
          onSuccess = {},
          onError = {}  
        )
    I'm not great with coroutines, but I assume it would look something like:
    async {
      try {
        val quote = quoteService.getQuote().await()
        response.write(quote)
      catch(_: Exception) {}
    }
    Is it just about the style of programming, or do coroutines offer something major over the other approaches? I see a few places that mention coroutines are non-blocking, but they don't seem to be, at least not in the same way that non-blocking io works. Can anyone help clarify this?
    v
    u
    +1
    10 replies · 4 participants
  • j

    julienviet

    10/23/2017, 8:32 AM
    a system property is mentionned in this issue to ease the debugging of stacktraces in coroutines : https://github.com/Kotlin/kotlinx.coroutines/issues/74 . Somebody knows if it was ever implemented ?
    e
    8 replies · 2 participants
  • e

    elizarov

    10/23/2017, 11:24 AM
    You get better with channles/actors only when the channels are not hidden behind methods, so you can can build async processing pipelines with them.
    u
    1 reply · 2 participants
  • u

    uli

    10/23/2017, 6:47 PM
    Yes, looks like it 🙂 The beauty of coroutines is, that you have a sequential flow, even with suspension points.
    m
    8 replies · 2 participants
  • d

    dave08

    10/23/2017, 8:24 PM
    Elizarov answered that channels are async, im trying to approach from the sequence end to understand if they are not async, how are they different from regular kotlin sequences?
    v
    g
    15 replies · 3 participants
Powered by Linen
Title
d

dave08

10/23/2017, 8:24 PM
Elizarov answered that channels are async, im trying to approach from the sequence end to understand if they are not async, how are they different from regular kotlin sequences?
v

voddan

10/23/2017, 8:27 PM
They are the same. Seriously
In other words, a sequence is a state machine. You ask for an element, and it gives you a value depending on its state. Kotlin coroutines is a general way to build such state machines, and in its simplest form they can be sequences.
d

dave08

10/23/2017, 8:30 PM
So why did they bother making it part of coroutine core?
v

voddan

10/23/2017, 8:33 PM
Because why not, literally 🙂
d

dave08

10/23/2017, 8:36 PM
Oh 😲
v

voddan

10/23/2017, 8:38 PM
I agree that
buildSequence
is kinda a side use of Coroutines, but it is nice to have, especially since :kotlin: is trying to compete withy Python
d

dave08

10/23/2017, 8:42 PM
Isnt a regular sequence enough to compete?
Thanks for clearing me up on this, I thought I was getting things wrong... 😄
g

groostav

10/24/2017, 5:46 PM
@voddan I dont know If I would be as fatalistic as that, the coroutine implementation embeds what is often a huge part of the state machine dispatching logic for you. simply-put, the old school
generateSequence
will often require a
when
statement where
buildSequence
doesn't. I've used this for test-data where I want lazy creation of elements (IE, I cant simply enumerate them eagerly), consider:
val resources = buildSequence {
  yield(makeExpensiveResourceOne())
  yield(makeExpensiveResourceTwo())
}
with generate sequence
//no good, its eager
val resources = listOf(makeResourceOne(), makeResourceTwo()).toSeq()


val resources = (1 .. 2).toSeq().map {
  when(it) {
    1 -> makeExpensiveResourceOne()
    2 -> makeExpensiveResourceTwo()
  }
}
d

dave08

10/24/2017, 5:55 PM
@groostav Nice, but one could always do:
val resources = listOf(::makeExpensiveResourceOne,::makeExpensiveResourceTwo).toSeq().map { it() }
g

groostav

10/24/2017, 10:26 PM
this is true
and its true generally @dave08
you will almost always find functional ways to achieve things that you could probably express a little bit more traditionally/emperically with coroutines
My personal favourite place for coroutines (and in a place where i have zero experience with them) is with the Unity game engine where you cao do things like
async void doAnimation(){
  characterModel.displayedFrame = hitFrame[0]
  characterModel.location -= 5
  nextFrame() //suspending function

  characterModel.displaedFrame = hitFrame[1]
  characterModel.location -= 2
  nextFrame()
}
d

dave08

10/25/2017, 2:22 AM
I think i figured a use case for coroutine sequences over regular ones: when the generation process is more involved
buildSequence
is better than regular Kotlin sequence generators, like with yield on conditions and yieldall that can produce many next values in one shot that can be iterated through one by one. Whereas regular sequences can generate only the next value from an isolated computation or as an accumulation of a previous result apon iterating through each value So for concurrency there are no advantages over sequences, but there are more options on how to actually generate them.
View count: 5