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

    bjartek

    01/10/2018, 8:21 PM
    i often find myself writing the following like code /code runBlocking(threadPool) { someList.map{ async(threadPool) { doOperation(it)}}.map{it.await()}} is there some better way to write this? basically i have a list and i want to process each element in a a seperate coroutine but i want to specify the threadPool used
    g
    • 2
    • 2
  • b

    bdawg.io

    01/11/2018, 8:05 PM
    I agree. It’s a beautiful way of life. With the discussions of it’s removal from other library packages, I just wanted to make sure it was still going to be around 🙂
    s
    • 2
    • 1
  • j

    jmfayard

    01/13/2018, 9:35 AM
    @eddy_wm ^^
    👏 1
    e
    • 2
    • 1
  • e

    elizarov

    01/13/2018, 9:36 AM
    📣 📣 📣
    kotlinx.coroutines
    version
    0.21.1
    is released with bug fixes and performance improvements for both JVM and JS. See here for details: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/0.21.1
    🎉 16
    s
    a
    n
    • 4
    • 5
  • e

    eddy_wm

    01/14/2018, 10:15 AM
    Hi. Is it possible in Kotlin coroutines to launch a thousand of coroutines in a way that when the first completes its execution all of other coroutines should also stop. It's quite a common pattern for parallel CPU mining algorithms.
    v
    • 2
    • 6
  • m

    mcastiblanco

    01/15/2018, 2:33 AM
    @eddy_wm here is a simple example of it
    fun main(args: Array<String>) = runBlocking{
        val dispatcher = newFixedThreadPoolContext(10, "myPool")
    
        val jobs = ArrayList<Job>()
        for (i in 1..10) {
            jobs.add(launch(dispatcher) {
                println("Running in ${Thread.currentThread().name}")
                Thread.sleep(2000)
            })
        }
    
        for (job in jobs) {
            job.join()
        }
    }
    which then prints something like
    Running in myPool-1
    Running in myPool-2
    Running in myPool-3
    Running in myPool-4
    Running in myPool-5
    Running in myPool-6
    Running in myPool-7
    Running in myPool-8
    Running in myPool-9
    Running in myPool-10
  • m

    mcastiblanco

    01/15/2018, 2:36 AM
    @eddy_wm take into account that creating threads is expensive tho, the idea is whenever possible avoid blocking operations
    👍 1
    e
    • 2
    • 1
  • g

    gildor

    01/15/2018, 2:37 AM
    @eddy_wm But you should bear in mind that need Thread.sleep only in one situation: if you want emulate blocking call or expensive computations
    e
    • 2
    • 2
  • k

    kenkyee

    01/15/2018, 4:18 PM
    think of it as cooperative looping...children have to check a flag to exit their loops
    e
    d
    m
    • 4
    • 8
  • r

    r4zzz4k

    01/15/2018, 8:10 PM
    I have several functions like this one chained (there may be one or multiple `send`s inside). I'm not sure if this is proper way to break down processing of the data stream. Am I doing something wrong by chance?
    fun processor(input: ReceiveChannel<A>): ReceiveChannel<B> = produce {
        input.consumeEach {
            ...
            send(...)
        }
    }
    And if not, is there more idiomatic way to do this chaining?
    d
    • 2
    • 2
  • r

    r4zzz4k

    01/16/2018, 4:09 PM
    Do I understand correctly that there is no way to peek the last value from
    ConflatedChannel
    without removing it?
    l
    • 2
    • 3
  • r

    r4zzz4k

    01/16/2018, 7:31 PM
    Of course I could add a level of indirection by using
    CompletableDeferred
    , thank you very much for this suggestion! Here's the final sample: https://try.kotlinlang.org/#/UserProjects/dsu5vhgcr0ls2h0flirmp3pf9g/ga94a9qaeq9e6v6s5bncbb75k3
    b
    • 2
    • 13
  • l

    lovis

    01/17/2018, 8:31 AM
    short question: do i still have to
    enable
    coroutines? (e.g.
    kotlin.experimental.coroutines = 'enable'
    in build.gradle) I can’t seem to find it in the documentation and appearently it’s working without it. (but then again I’m not using the whole feature set)
    r
    • 2
    • 3
  • e

    elizarov

    01/19/2018, 4:06 PM
    See https://youtrack.jetbrains.com/issue/KT-17609
    l
    • 2
    • 10
  • r

    r4zzz4k

    01/19/2018, 7:27 PM
    Do I understand correctly that I'm not able to mark lambda declaration as
    suspend
    ? I.e. there is no way to avoid explicit type here:
    val lambda: suspend (String) -> Unit = { input: String -> /* body */ }
    e
    • 2
    • 2
  • e

    elizarov

    01/20/2018, 10:41 AM
    It simply means that the function delegates to the
    CoroutineDispatcher
    . For example, if you are running your coroutines under Android
    UI
    dispatcher, then it users Android-specific API to schedule execution after a specified time interval passes.
    a
    • 2
    • 1
  • d

    dh44t

    01/21/2018, 1:40 PM
    Functional Kotlin will have it https://www.packtpub.com/application-development/functional-kotlin
    👍 3
    w
    • 2
    • 3
  • j

    jw

    01/22/2018, 9:51 PM
    let's say I have a
    suspend fun sum(): Long
    inside which I have a reference to something with the method
    suspend fun consume(consumer: suspend (Long) -> Unit)
    . The implementation is the obvious thing:
    var sum = 0L
    numbers.consume { sum += it }
    return sum
    Now let's say I want to specify a maximum number of numbers. How can I cause the
    numbers.consume
    to stop pushing numbers at me once that max is hit?
    e
    • 2
    • 1
  • b

    bj0

    01/22/2018, 11:51 PM
    the error isn't always the same, but it's always on the same call to
    actor
    e
    • 2
    • 5
  • e

    elizarov

    01/23/2018, 4:20 PM
    @kevinherron Can you, please, create a new issues to summarize your use-cases https://github.com/Kotlin/kotlinx.coroutines/issues It would be extremely helpful if you provide specific examples of boilerplate that you’ve found yourself writing multiple times.
    k
    • 2
    • 2
  • g

    gildor

    01/24/2018, 8:32 AM
    @marcinmoskala You cannot use runBlocking the same way as on JVM. JS is single threaded. @elizarov Mentioned that he plans to delete it to avoid confusion
    👍 2
    m
    • 2
    • 1
  • c

    christophsturm

    01/24/2018, 1:15 PM
    is there a nonblocking http client that supports coroutines? i would like to create 1000 http requests in parallel. in java i would probably use jetty-http-client
    s
    k
    • 3
    • 4
  • e

    elizarov

    01/24/2018, 9:38 PM
    📣 📣 📣
    kotlinx.coroutines
    version
    0.22
    released.
    AbstractCoroutine
    class now has public and stable API for extensions/integration. https://github.com/Kotlin/kotlinx.coroutines/releases/tag/0.22
    :kotlin: 15
    🎉 12
    l
    • 2
    • 4
  • m

    mcastiblanco

    01/25/2018, 5:29 AM
    @elizarov actually I am still able to reproduce it in
    0.22
    and Kotlin
    1.2.21
    . I put the comment on the ticket 👍
    👍 1
    e
    • 2
    • 4
  • e

    enleur

    01/26/2018, 12:00 AM
    https://gist.github.com/enleur/1b552483c7a540c7d29ea1f9c64f5e06 @elizarov is this the right way to use MDC context with coroutines?
    e
    • 2
    • 2
  • l

    louiscad

    01/26/2018, 4:35 PM
    Hi! I have a non suspending function that has a callback where errors are received, and I want any incoming error to stop the coroutine it may have been launched in. My code currently looks like this: 1️⃣
    fun SomeReceiver.someFunction(parentJob: Job) {
        someNonSuspendingCode()
        setOnErrorListener { errorCode ->
            parentJob.cancel(SomeException(errorCode))
        }
    }
    I'm wondering if I should make it a
    suspend fun
    so I can get the current job from the coroutineContext (currently available in the intrisics package) and remove this not so nice (IMHO)
    parentJob
    parameter. If I did, it'd look like this: 2️⃣
    suspend fun SomeReceiver.someFunction() {
        val currentJob = coroutineContext[Job]!!
        someNonSuspendingCode()
        setOnErrorListener { errorCode ->
            currentJob.cancel(SomeException(errorCode))
        }
    }
    e
    • 2
    • 1
  • r

    r4zzz4k

    01/26/2018, 5:02 PM
    For debugging purposes I want to log every element going through the channel. Is there any better way to do it than this?
    class LoggingLinkedListChannel<E>(private val tag: String): LinkedListChannel<E>() {
    	override fun offerInternal(element: E): Any {
    		println("[$tag] $element")
    		return super.offerInternal(element)
    	}
    }
    val chan = LoggingLinkedListChannel<Int>("tag") // was Channel<Int>(Channel.UNLIMITED)
    Is it even valid way to do this? It seems to be working for my simple use-case, but still. As another way to do that was trying to get this working with
    .map { println(it); it }
    , but it throws away capacity as it's effectively creates another channel.
    e
    • 2
    • 2
  • e

    enleur

    01/26/2018, 5:11 PM
    fun <E> ReceiveChannel<E>.onEach(context: CoroutineContext = Unconfined, action: (E) -> Unit): ReceiveChannel<E> =
        produce(context) {
            consumeEach {
                action(it)
                send(it)
            }
        }
    r
    • 2
    • 1
  • o

    Olekss

    01/27/2018, 4:41 PM
    hey do I understand correctly that to use Sender, Receiver Channels I have to implement those interfaces in case if I want - for example - have JeroMQ server/client listening and representing that channel of receiving/sending information?
    e
    • 2
    • 1
  • l

    louiscad

    01/27/2018, 9:18 PM
    Hi @elizarov, s kotlinx.coroutines availability on try.kotl.in planned?
    v
    r
    • 3
    • 3
Powered by Linen
Title
l

louiscad

01/27/2018, 9:18 PM
Hi @elizarov, s kotlinx.coroutines availability on try.kotl.in planned?
v

voddan

01/27/2018, 9:29 PM
I think it has been working with the right imports
👍🏽 1
l

louiscad

01/29/2018, 8:19 AM
You're right! I opened an issue to improve coroutines presence on the try website: https://youtrack.jetbrains.com/issue/KT-22561
👍 1
r

r4zzz4k

01/29/2018, 1:30 PM
One thing I found not working there: If you create own dispatcher based on Executor, you won't be able to shutdown it in the end due to security restrictions. Not sure if that's okay or not, because it isn't related to coroutine dispatchers directly.
View count: 2