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

    Olekss

    02/12/2018, 12:28 PM
    I have a question... situation not fully clear, but the observation is this: I invoke 3 "nodes" which each start 2 launch coroutine builders.... While each node is starting I do Thread.sleep(5000) on may thread (I run the stuff on main function) But what I observe is that 3rd node does not start until first one is destroyed (tus freeing some threads) As I told each node has 2 launchers where one is infinite cycle waiting on server connection (nonbloicking) incomming messages, but 2nd launch does .receive on channel So my version is that first 2 nodes somehow exhaust ForkJoin pool and my 3rd node does not start until I free something... can it be?
    d
    k
    l
    • 4
    • 14
  • g

    gildor

    02/14/2018, 8:22 AM
    Something like that?
    val channel = produce {
      delay(500) // only one value with delay, but can be wrapped to some loop)
      send("some value")
    }
    for (value in channel) {
       //Do something
    }
    Depends on your case of course. What exactly do you want to do?
    👍 1
    a
    • 2
    • 3
  • b

    bj0

    02/14/2018, 9:14 PM
    the
    CompletableDeferred
    was completely internal, I was using
    return deferred.await()
    and
    object.onCallback {deferred.complete(it)}
    d
    • 2
    • 31
  • k

    koufa

    02/15/2018, 10:37 AM
    Could someone explain the concrete difference between a CoroutineDispatcher and a CoroutineInterceptor please?
    a
    • 2
    • 1
  • l

    leandrodev

    02/15/2018, 12:54 PM
    Hello, can someone help me with kotlin channels? I wanted to create a behavior similar to
    ConflatedBroadcastChannel
    , but discarding the event when it's broadcasted. Is there any channel implementation that is capable of that?
    e
    • 2
    • 4
  • c

    chirag

    02/16/2018, 7:57 AM
    Hey all ,Just need an advice here using Coroutines in kotlin : Should we call async methods in properties of class, and await in class methods whenever they would be called For Ex -
    class DataAccess(val id:String) {
        
        private val fooAsync = async { fetchDataFromTableA(id) }
        private val barAsync = async { fetchDataFromTableB(id) }
    
        fun getData(): Data {
            var foo =fooAsync.await()
            var bar = barAsync.await()
            
            return compute(foo,bar)
        }
    }
    Just want to know ,Is it right way to do it ?
    j
    • 2
    • 11
  • u

    uhe

    02/16/2018, 9:49 AM
    is there an example anywhere showcasing the difference between
    suspendAtomicCancellableCoroutine
    and
    suspendCancellableCoroutine
    ?
    j
    u
    • 3
    • 12
  • s

    sdeleuze

    02/16/2018, 10:07 AM
    Hey, what is the recommended way to convert a
    ReceiveChannel
    to a shared
    BroadcastChannel
    ? I try to convert my Reactor SSE example to Coroutines where I want to use a single stream from my Mongo database to a shared broadcasted stream to browsers. Reactor version: https://github.com/sdeleuze/spring-kotlin-deepdive/blob/step3/src/main/kotlin/io/spring/deepdive/web/ArticleController.kt#L51-L52. Coroutines version without the broadcast feature: https://github.com/sdeleuze/spring-kotlin-deepdive/blob/step3-coroutine/src/main/kotlin/io/spring/deepdive/web/ArticleController.kt#L52-L57.
    j
    • 2
    • 3
  • t

    themishkun

    02/19/2018, 6:15 PM
    Anyone has experince moving from rxjava to coroutines? Any tips? Do I need that or not? Our app is written clean arch style, with repos, interactors presenters and rx binding it all together.
    d
    • 2
    • 1
  • d

    dh44t

    02/20/2018, 10:12 AM
    Multithreading is a lot easier on plain Coroutines IMHO
    ➕ 5
    g
    • 2
    • 3
  • t

    themishkun

    02/20/2018, 11:40 AM
    Okay, I might have overlooked the “channels” thing, it looks pretty promising and resolving 90% of tasks inside our android app. Thank you for rx vs coroutines opinions, I should research more
    j
    w
    • 3
    • 4
  • a

    asad.awadia

    02/20/2018, 4:09 PM
    Is there a way to launch a coroutine that 'listens' to stdin input while the rest of the program runs? something like
    launch { while(true) { //listen to keyboard input and do stuff } }
    j
    • 2
    • 2
  • z

    zak.taccardi

    02/20/2018, 11:50 PM
    yeah, I’d want multiple subscribers 😕
    j
    • 2
    • 1
  • l

    louiscad

    02/21/2018, 10:48 AM
    Hi, does anyone knows if kotlinx.coroutines on #kotlin-native are planned anytime soon now that multiplatform support is there? See also related issue: https://github.com/Kotlin/kotlinx.coroutines/issues/246
    e
    • 2
    • 1
  • j

    jkbbwr

    02/21/2018, 4:20 PM
    asyncHandler(this::ping)
    Will complain that KFunction<RoutingContext, Unit> doesnt match suspend (RoutingContext) -> Unit
    j
    • 2
    • 4
  • d

    dsgryazin

    02/21/2018, 7:06 PM
    Questions on
    Mutex.kt
    internal class MutexImpl(locked: Boolean) : Mutex, SelectClause2<Any?, Mutex> {
        // State is: Empty | LockedQueue | OpDescriptor
        // shared objects while we have no waiters
        private val _state = atomic<Any?>(if (locked) EmptyLocked else EmptyUnlocked)
    
        // resumeNext is: RESUME_QUIESCENT | RESUME_ACTIVE | ResumeReq
        private val _resumeNext = atomic<Any>(RESUME_QUIESCENT)
    
        public override val isLocked: Boolean get() {
            _state.loop { state ->
                when (state) {
                    is Empty -> return state.locked !== UNLOCKED
                    is LockedQueue -> return true
                    is OpDescriptor -> state.perform(this) // help
                    else -> error("Illegal state $state")
                }
            }
        }
    1. Please, explain, what is meant by each of
    Empty | LockedQueue | OpDescriptor
    ? 2. What is for
    resumeNext is: RESUME_QUIESCENT | RESUME_ACTIVE | ResumeReq
    ? 3. What means the `help`comment in
    is OpDescriptor -> state.perform(this) // help
    ? 😅
    e
    • 2
    • 5
  • b

    bdawg.io

    02/21/2018, 7:43 PM
    Does anyone have any suggestions on how to create a coroutine that tracks the completion of other jobs before launching a final coroutine? ie, I have two jobs that are running: Job A, Job B I have a third job, that must wait for A and B to finish: Job C
    / -- [ Job A ] -- \
    ----                  ---- [ Job C ]
        \ -- [ Job B ] -- /
    d
    e
    j
    • 4
    • 10
  • j

    jw

    02/22/2018, 4:33 AM
    i'm using a ConflatedChannel for a view model so that it can be updated while there's no view to consume but when the view comes back it gets the latest. This works great, except it appears that the incoming view always has to suspend to get that buffered instance. This means that the view state gets restored before the data (which then effectively drops the state). Is there a way to have a consumer of a conflated channel receive the last known value (if any) synchronously inside an unconfined coroutine? Or is there something else built-in that I can use for this?
    👍 1
    d
    • 2
    • 4
  • p

    Paul Woitaschek

    02/22/2018, 7:33 AM
    @elizarov were you able to check that coroutine bug where it's throwing uncaught exceptions outside the RX chain?
    e
    • 2
    • 2
  • a

    asad.awadia

    02/23/2018, 12:40 AM
    @elizarov Just out of curiosity - how does one go about adding support for 'suspend' functions to their own interface of their library - dunno if the question makes sense --- https://twitter.com/JakeWharton/status/964556938322341894
    👍 1
    g
    j
    • 3
    • 10
  • j

    jkbbwr

    02/26/2018, 7:33 PM
    Ignore above
    r
    • 2
    • 2
  • k

    krotki

    02/27/2018, 1:17 PM
    You can also have a look at ConflatedBroadcastChannel: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-conflated-broadcast-channel/index.html
    j
    b
    • 3
    • 9
  • l

    louiscad

    02/27/2018, 1:36 PM
    Hi, where can I find the suspension point icon that we can see in the IDE (in vector format or high res png)?
    h
    d
    • 3
    • 3
  • w

    withoutclass

    02/27/2018, 3:28 PM
    has anyone run into needing to debounce a channel yet?
    j
    d
    • 3
    • 5
  • p

    pablisco

    02/27/2018, 4:03 PM
    Is there, or are there any plans to do functional operators for channels? (map, filter, etc)
    j
    • 2
    • 3
  • b

    bj0

    02/27/2018, 4:15 PM
    @elizarov oh ok, I didn't know the behavior of
    withContext
    was different, is that difference documented?
    e
    • 2
    • 3
  • e

    elizarov

    02/27/2018, 7:03 PM
    That just burns CPU while it waits. Are you sure you want that?
    j
    • 2
    • 2
  • m

    miha-x64

    02/27/2018, 8:36 PM
    Is there a way to set a generic upper bound to
    suspend Function<R>
    ? Exactly
    Function
    because I don't know yet how many arguments it will accept. Use-case: hierarchical web routing.
    interface Address<T, HANDLER : suspend Function1<Unit>>
    class Address1<T> : Address<T, suspend (T) -> Unit>
    handles
    /{a}/
    addresses, fetches an object with
    a
    path, supplies fetched object to handler
    class Address2<T, U> : Address<U, suspend (T, U) -> Unit>
    handles
    /{a}/{b}/
    addresses, fetches
    T
    bound to
    a
    path, fetches its child
    U
    bound to
    b
    path, supplies them to handler and so on...
    • 1
    • 1
  • j

    Jonathan

    02/28/2018, 9:03 AM
    Hi, is there an empty ReceiveChannel available in kotlinx.coroutines ?
    e
    • 2
    • 4
  • d

    diesieben07

    02/28/2018, 12:51 PM
    How do I properly send to a
    SendChannel
    which might be closed? Do I have to just catch the
    ClosedSendChannelException
    ?
    j
    b
    • 3
    • 50
Powered by Linen
Title
d

diesieben07

02/28/2018, 12:51 PM
How do I properly send to a
SendChannel
which might be closed? Do I have to just catch the
ClosedSendChannelException
?
j

Jonathan

02/28/2018, 12:52 PM
If it is closed, you cannot send elements to it by definition. So yes, you just have to catch the exception and deal with it.
d

diesieben07

02/28/2018, 12:53 PM
Ok. Then maybe I am going about this wrong. I have a (potentially infinite) source and I want the receiver to be able to tell "hey, I don't need anymore". Is
close
the correct way?
j

Jonathan

02/28/2018, 12:54 PM
If you don't want elements it is okay to close it. But of course it won't be infinite anymore. Note that you can also test
isClosedForSend
to know if it is currently close.
Or depending on your use-case, you maybe are looking for a
BroadcastChannel
?
If using a broadcast you would never close the broadcast, but the receiver could close the opened subscription
d

diesieben07

02/28/2018, 12:55 PM
Yes, I can test
isClosedForSend
, but that's a race condition, is it not (tocttou)?
Well, I need to close the channel, because there are resources associated with it (network stuff...)
j

Jonathan

02/28/2018, 12:57 PM
Then, If possible I would recommend to create the channel with
produce
. this function will handle everything, like closing when done, when cancelled and when failed.
d

diesieben07

02/28/2018, 12:59 PM
That only moves the problem does it not? The channel still has no
sendIfPossibleOrReturnFalse
method.
If so I could just do
do {
    val element = TODO() // compute next element
} while (channel.sendIfPossibleOrReturnFalse(element))
That's what I am trying to achieve.
j

Jonathan

02/28/2018, 1:02 PM
Do this instead:
produce {
	while(isActive) {
		val element = TODO()
		send(element)
	}
}
Then
produce
will handle it for you
d

diesieben07

02/28/2018, 1:02 PM
Will it though? What if the receiver closes the channel during whatever
TODO
is? Then
send
will throw...
j

Jonathan

02/28/2018, 1:04 PM
If the consumer cancel the channel,
send
will throw a
CancelledException
.
d

diesieben07

02/28/2018, 1:04 PM
Yes...
Which I do not want. I want the receiver to be able to tell the producer to stop.
I do not want the receiver to be able to tell the producer to blow up with an exception.
Also, with this
produce
approach, how do I terminate the underlying thread (
newSingleThreadContext
) when the channel is closed?
j

Jonathan

02/28/2018, 1:07 PM
CancelledException
will be consumed by
produce
as it is a normal reason to be terminated. If you use resources you should anyway always ensure they are closed in case of exception. (same as if you wouldn't use coroutines)
d

diesieben07

02/28/2018, 1:08 PM
Okay, so then that part is sorted. How do I close the thread context though?
j

Jonathan

02/28/2018, 1:08 PM
If you use
newSingleThreadContext
you have of course to ensure that is terminated even in case of exception.
d

diesieben07

02/28/2018, 1:08 PM
Yes, but... how can I terminate it from inside the produce? Can I terminate it from "inside itself"?
Just
use
will not work, will it?
j

Jonathan

02/28/2018, 1:10 PM
Mmh. that's a good question, I've never did that
d

diesieben07

02/28/2018, 1:11 PM
I.e. this:
newSingleThreadContext().use { ctx ->
    return produce(ctx) {
    }
}
won't work, right?
j

Jonathan

02/28/2018, 1:11 PM
no it won't work
It may terminate the dispatcher to early
d

diesieben07

02/28/2018, 1:12 PM
Yeah that's what I was thinking.
I guess I will have to pass the context into the method that returns
produce
?
j

Jonathan

02/28/2018, 1:14 PM
fun startProducer() {
  val context = newSingleThreadContext("my dispatcher")

  val result = produce(context) {
    context.use {
      send(1)
      send(2)
      send(3)
    }
  }
}
this should work. But I wonder if there is a better way of doing it.
d

diesieben07

02/28/2018, 1:14 PM
I am doing it outside now, and passing
coroutineContext
as a parameter.
thanks for your help!
j

Jonathan

02/28/2018, 1:15 PM
By the way it may be not necessary in the future to terminate the dispatcher. see: https://github.com/Kotlin/kotlinx.coroutines/issues/261
b

bj0

02/28/2018, 4:35 PM
why does it need to be outside produce?
produce {
    newSingleThreadContet("dispatch").use {
        while(isActive)
            send(TODO())
    }
}
j

Jonathan

02/28/2018, 4:36 PM
@bj0, in your example
produce
use
CommonPool
b

bj0

02/28/2018, 4:37 PM
ah right
you can toss a
withContext
in there
outside the
while
loop
j

Jonathan

02/28/2018, 4:38 PM
Yes indeed. But it is simpler to simply give the context as an argument of
produce
b

bj0

02/28/2018, 4:41 PM
I don't know, I think it's less simple to have to create an essentially local variable outside the scope of where it's used.
seems leaky
j

Jonathan

02/28/2018, 4:46 PM
Yes, but if it is really local, what is the point creating a single thread context ? Why not simply use the common pool ?
I don't see the point of creating a thread pool if it is not to be shared by many coroutines.
b

bj0

02/28/2018, 4:50 PM
thats an implementation detail and I don't know what his program's context is.
j

Jonathan

02/28/2018, 4:56 PM
I'm not sure. I feel that's there is something not correct with this approach. Basically it could leads to a lot of thread creation which is very expensive and bad practice. The good practice is to use thread pool in order to reuse the threads. I would rather create a global ThreadPool like
val MyThreadPool = newSingleThreadPool("my thread pool")
and use it for the whole life of the application. calling
produce(MyThreadPool) {}
d

diesieben07

02/28/2018, 5:00 PM
Yes, I agree with @Jonathan. That's why I ended up passing the
CoroutineContext
into my own method and then pass it on to
produce
.
b

bj0

02/28/2018, 5:07 PM
if you're doing that you're not going to clean it up when one producer closes though
d

diesieben07

02/28/2018, 5:08 PM
I have the whole thing (produce and consume) in a
newSingleThreadContext().use {}
. It is closed properly.
b

bj0

02/28/2018, 5:18 PM
i mean if you're going to "create a global ... and use it for the whole life of the application", obviously use case matters
View count: 1