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

    cy

    06/14/2018, 9:15 AM
    📣
    kotlinx.coroutines
    version
    0.23.2
    fixes bug in
    kotlinx-coroutines-io
    that causes content damage
    🤔 2
    t
    e
    b
    • 4
    • 3
  • p

    pakoito

    06/14/2018, 9:26 AM
    what is content damage?
    ➕ 1
    e
    • 2
    • 4
  • c

    coder82

    06/14/2018, 9:24 PM
    IDE Fatal Errors
    i
    e
    • 3
    • 2
  • e

    eygraber

    06/15/2018, 8:45 AM
    I'm still trying to wrap my head around coroutines, and I think I'm almost there. I'm thinking about it in terms of comparison to Rx. Is it safe to say that the practical differences there are: 1. Natural coding style vs streams/operators 2. Less allocation A. Therefore lower memory usage B. Therefore potential faster execution (less GC)
    e
    • 2
    • 1
  • s

    spand

    06/15/2018, 12:49 PM
    I need to lookup something by id asynchronously and limit it to one lookup per id. Would something like this be the way to do it?
    val cache = ConcurrentHashMap<Int, Deferred<String>>()
    
    suspend fun getById(id: Int) : String {
        return cache.computeIfAbsent(id) {
            async { asyncAction(id) }
        }.await()
    }
    
    suspend fun asyncAction(id: Int): String = TODO()
    d
    w
    +3
    • 6
    • 18
  • u

    uli

    06/16/2018, 5:43 PM
    Related question. Does await suspend if the deferred is already resolved?
    v
    • 2
    • 2
  • a

    ashdavies

    06/16/2018, 11:19 PM
    Will there be a
    filterIsInstance
    method available for
    ReceiveChannel
    ? If not, should I propose one as a PR? on KEEP or on the main repo?
    v
    • 2
    • 3
  • d

    Daniel Tam

    06/17/2018, 12:59 PM
    just out of curiosity.. are there plans to implement suspending semaphores like we currently have suspending mutexes? You can make a very basic one right now by sending/receiving from a channel with a finite capacity - but then there's also stuff like acquiring n semaphores, and optimizing by disabling fairness https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html
    g
    v
    • 3
    • 3
  • h

    hannesstruss

    06/17/2018, 5:45 PM
    I tried to implement
    rx.Observable.switchMap
    for Channels: https://gist.github.com/hannesstruss/927ec8120d7cb312d80685f230d50c6e It's kind of working ("just" deadlocking occasionally), but I found the way there to be very brittle, so much depends on using the right coroutine contexts in the right places. E.g. when not using
    Unconfined
    for
    produce
    in the
    transform
    function, the wrong channel will be selected in
    whileSelect
    and the outcome will be wrong. Any general hints on how to approach problems like that?
    v
    • 2
    • 3
  • p

    Paul Woitaschek

    06/18/2018, 7:19 AM
    Does it make sense to use coroutines for a worker queue like this?
    v
    • 2
    • 1
  • u

    uli

    06/18/2018, 1:34 PM
    Hi all, I was surprised to see, that canceling a job that is suspended in a
    consumeEach
    will execute code after the
    consumeEach
    . Is this expected behaviour? In the below example, if
    job.cancel()
    is called, while the job is waiting for new Items from
    receiveChannel
    it will print out
    Done
    job = launch(coroutineContext) {
                    receiveChannel.consumeEach { r ->
                        output.send(r)
                    }
                    println("Done")
                    output.close()
                }
    If relevant, I do have a self contained sample, which is an alternative implementation of @hannesstruss switchMap example. Please let me know if I should post it.
    v
    • 2
    • 1
  • h

    hannesstruss

    06/18/2018, 1:35 PM
    Sure, would love to see it 🙂
    u
    • 2
    • 1
  • u

    uli

    06/18/2018, 1:43 PM
    https://gitlab.com/snippets/1725697 Kind of hard to read due to all the log messages.
    • 1
    • 2
  • u

    uli

    06/18/2018, 3:01 PM
    And yet another question. Inside a
    produce
    , does `this.close()`cancel the producer? Is this documented?
    v
    • 2
    • 10
  • u

    uli

    06/18/2018, 3:42 PM
    Well, I ask, because I expected a `ClosedSendChannelException`on next send operation as is documented in the API docs, but I don't get to the next send operation but get a JobCanceledException before https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/close.html
    A channel that was closed without a cause throws ClosedSendChannelException on attempts to send or receive. A channel that was closed with non-null cause is called a failed channel. Attempts to send or receive on a failed channel throw the specified cause exception.
    Documentation for
    produce
    mentions:
    The running coroutine is cancelled when its receive channel is cancelled.
    But does not talk about the SendChannel being closed
    • 1
    • 1
  • e

    Evgeniy Zaharov

    06/20/2018, 3:19 PM
    with changing
    launch
    to
    async
    and
    join
    to
    await
    everything start to work as expect, I see all three catch (as described in https://github.com/Kotlin/kotlinx.coroutines/issues/61). But with
    launch
    its very strange that
    method-catch
    doesn’t call
    c
    v
    u
    • 4
    • 9
  • f

    Fabio Tudone

    06/21/2018, 1:01 PM
    Possible newbie question: does it make sense for regular threads and coroutines to communicate/cooperate and what's the best way to achieve that?
    g
    b
    +3
    • 6
    • 13
  • p

    pakoito

    06/23/2018, 7:52 PM
    I’m testing against a single thread pool for a given name, and I’ve found that the framework adds some coroutines-specific information to the name
    v
    e
    • 3
    • 2
  • p

    pakoito

    06/24/2018, 10:44 AM
    what is the coroutines equivalent of caching the current context to continue there at a later point? something like
    Scheduler.trampoline()
    l
    c
    • 3
    • 3
  • p

    pakoito

    06/24/2018, 1:03 PM
    what is a “restricted suspension coroutine”
    e
    • 2
    • 1
  • p

    pakoito

    06/24/2018, 1:04 PM
    what is a non-empty coroutine context, do you mean literally anything that isn’t Unconfined or EmptyCoroutineContext
    e
    • 2
    • 1
  • p

    pakoito

    06/24/2018, 1:24 PM
    I can give a smaller version
    e
    • 2
    • 3
  • d

    dave08

    06/24/2018, 3:34 PM
    I'm using an event queue based on a
    Channel
    like this:
    val eventQueue = Channel<ApplicationInstallRequest>()
    
    	init {
    		initEventProcessor()
    	}
    
    	private fun initEventProcessor() = launch(Unconfined) {
    		for (request in eventQueue) {
    			processRequest(request)
    		}
    	}
    
    	override fun onEvent(event: ApplicationInstallRequest) {
    		eventQueue.sendBlocking(event)
    	}
    from an Android SyncAdapter, but even when the sync is finished, the process keeps on going (some kind of leak...), does Unconfined have it's own thread or something?
    l
    d
    • 3
    • 33
  • d

    dave08

    06/25/2018, 4:26 PM
    Ok, I think I solved this with
    whileSelect
    , but what's the boolean that needs to be returned for? It doesn't look docuemented in the guide's examples..?
    e
    u
    • 3
    • 4
  • d

    dave08

    06/26/2018, 5:20 PM
    I think that maybe in this context of Process, the only blocking that really needs to be done is when retrieving the result of a command sent to the process, so maybe there could be some kind of logic to block only until idle for a certain amount of time and then just yield until the next command is sent...?
    l
    n
    • 3
    • 3
  • l

    littlelightcz

    06/27/2018, 8:06 AM
    Is there currently a way to call
    withContext(CommonPool) { ... }
    just like
    withContext { ... }
    ? (similarly as async { } can be called on default pool) However just
    withContext { ... }
    might seem confusing, so maybe it would be nice to add some shorthand with a different name for this if there isn't anything like that already 🙂
    g
    • 2
    • 2
  • d

    dave08

    06/27/2018, 1:17 PM
    I guess you're right, a
    Mutex
    will anyways protect that
    var syncRequested
    ... I don't need complex logic, just to squash the next bunch of requests to only one syncRequest... thanks! Right now, we're still on targetSdk 22 🙈 (I know I'll have to change that sooner or later)... But I don't want the sync to suddenly be stopped in the middle if the user goes out of the app, so how can it be foreground? @louiscad
    l
    • 2
    • 1
  • d

    Daniel Tam

    06/27/2018, 1:20 PM
    Let's say I have some complex message protocol that requires wrapping objects inside objects inside objects (e.g. IP headers on tcp headers on http headers on data). Let's say I want to construct an IP message. Does anyone have any idea what will have better performance? (I suspect the first): 1. passing a lambda from the IP layer to the TCP layer, then wrapping it in a lambda and passing it to the HTTP layer, then wrapping it in a lambda and passing it to the layer that generates data. I.e. the data generation layer can just directly invoke the method to construct+send an IP message 2. passing a channel (or using producer/actor) between each layer, then spawning a coroutine for each layer to wrap and forward the data. I.e. the data generation layer creates its data and sends it through a channel to the HTTP layer, which then wraps it and sends it to the TCP layer, etc.
    g
    • 2
    • 1
  • d

    dave08

    06/27/2018, 1:23 PM
    Nice! And
    LifecycleService
    also manages its own thread?
    l
    • 2
    • 1
  • r

    rocketraman

    06/27/2018, 3:23 PM
    I have a coroutines-based API (ktor) that uses
    ByteReadChannel
    that I need to adapt to a rx2 API that uses
    Flowable<ByteBuffer>
    . Here are the methods I've come up with, with some guidance from @Deactivated User and @cy on #ktor, to adapt these in both directions -- these seem to work but opinions on correctness, efficiency, and style are welcome: Adapting
    Flowable<ByteBuffer>
    to
    ByteReadChannel
    suspend fun Flowable<ByteBuffer>.toByteReadChannel(parent: Job = Job()) = writer(Unconfined, parent = parent, autoFlush = true) {
      try {
        this@toByteReadChannel.consumeEach {
          channel.writeFully(it)
        }
      } catch (e: Throwable) {
        channel.close(e)
      }
    }.channel
    and in the other direction:
    suspend fun ByteReadChannel.toFlowable(): Flowable<ByteBuffer> {
      return rxFlowable {
        this@toFlowable.lookAheadSuspend {
          consumeEachRemaining {
            // we have to make a copy as the ByteBuffer here comes from a reused ring buffer
            this@rxFlowable.channel.send(it.copy())
            true
          }
          this@rxFlowable.close()
        }
      }
    }
    Note the
    copy()
    in the second code snippet. I don't like this but don't know how to get rid of it.
    • 1
    • 1
Powered by Linen
Title
r

rocketraman

06/27/2018, 3:23 PM
I have a coroutines-based API (ktor) that uses
ByteReadChannel
that I need to adapt to a rx2 API that uses
Flowable<ByteBuffer>
. Here are the methods I've come up with, with some guidance from @Deactivated User and @cy on #ktor, to adapt these in both directions -- these seem to work but opinions on correctness, efficiency, and style are welcome: Adapting
Flowable<ByteBuffer>
to
ByteReadChannel
suspend fun Flowable<ByteBuffer>.toByteReadChannel(parent: Job = Job()) = writer(Unconfined, parent = parent, autoFlush = true) {
  try {
    this@toByteReadChannel.consumeEach {
      channel.writeFully(it)
    }
  } catch (e: Throwable) {
    channel.close(e)
  }
}.channel
and in the other direction:
suspend fun ByteReadChannel.toFlowable(): Flowable<ByteBuffer> {
  return rxFlowable {
    this@toFlowable.lookAheadSuspend {
      consumeEachRemaining {
        // we have to make a copy as the ByteBuffer here comes from a reused ring buffer
        this@rxFlowable.channel.send(it.copy())
        true
      }
      this@rxFlowable.close()
    }
  }
}
Note the
copy()
in the second code snippet. I don't like this but don't know how to get rid of it.
One update to this: the explicit call to
this@rxFlowable.close()
was occasionally causing the library consuming the
Flowable
to throw an error. I've removed it, but is that ok to do in this case?
View count: 13