https://kotlinlang.org logo
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
benchmarks
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
confetti
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
lincheck
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
Title
l

louiscad

05/09/2019, 3:57 PM
Hi, did anyone combine the values from several `ReceiveChannel`s? What approach did you take?
k

kevin.cianfarini

05/09/2019, 4:46 PM
You could create a subclass of channel that takes vararg amounts of channels as a constructor param. For each channel, create a coroutine and
recieve
the element from that channel. Each time you receive,
send
to
this
channel
d

Dominaezzz

05/09/2019, 5:15 PM
I usually redesign. If I can't be arsed I use
select
.
👍 1
p

Paul Woitaschek

05/09/2019, 6:24 PM
Use asFlow and then combineLatest
b

bj0

05/09/2019, 8:45 PM
I use to use
select
in a
produce
, but I haven't looked at any of the new
Flow
stuff
l

louiscad

05/09/2019, 10:24 PM
Oh, I forgot to mention that all channels have different types and that I want to combine them into a data class sent/broadcast to a new channel each time one new value is received
g

gaetan

05/09/2019, 10:44 PM
@louiscad is asking a question on coroutines channel. Must be a tough one. Sorry for the noise. 😉
😅 1
b

bohsen

05/10/2019, 5:53 AM
@gaetan Pretty sure he'll ace the implementation though. 😜 Also sorry for noise.
🤔 1
b

bj0

05/10/2019, 5:57 AM
again, fairly easy to do with
select
and
produce
l

louiscad

05/10/2019, 7:23 AM
My current implementation is 47 lines of boilerplate code (not counting imports, no comments/KDoc lines) to combine 4 channels, each of different element types into a data class broadcast in a new
ConflatedBroadcastChannel
. I wish I could have a shorter solution that could scale better, that's why I asked. Also, I have no clue how I can do this with
select
and
produce
.
d

Dominaezzz

05/10/2019, 8:20 AM
What do you mean by combine? You want to get an item from each one, put all the items in a data class with 4 fields and then return the instance? Why not just call receive on each channel. Or you want to wait for the the first item from any channel and return a transformation/map of the item?
l

louiscad

05/10/2019, 10:22 AM
For now, that's what I do, I have a call to receive for each channel, I keep the last received value and each time I receive on new value for any of each channel, I update the last value and update the data class for all last values to be broadcast. I wish I found a more generic or less verbose way to do it for just 4 channels. It's basically over 10 lines of code per channel for now, and I use a few extensions
d

Dominaezzz

05/10/2019, 10:26 AM
How about
DataClass(channel1.receive(), channel2.receive(), channel3.receive(), channel4.receive())
?
l

louiscad

05/10/2019, 10:28 AM
I also need updates, when only one of the channels produces a new value, I need a new dataclass with the last values previously received from the other channels.
d

Dominaezzz

05/10/2019, 10:30 AM
Oh I get it now, you need a stream of latest values.
https://pl.kotl.in/AGzcQBHsL . Doesn't handle input channels closing though.
❤️ 1
b

bj0

05/11/2019, 7:26 AM
Yea that's basically what I had in my mind, but with
= produce {
👍 1
l

louiscad

05/13/2019, 7:43 AM
Here's a rather generic approach inspired by the snippet Dominic shared:
fun <E1, E2, R> CoroutineScope.combineLatest(
    one: ReceiveChannel<E1>,
    two: ReceiveChannel<E2>,
    transform: (one: E1, two: E2) -> R
): ReceiveChannel<R> {
    val output = Channel<R>(capacity = Channel.CONFLATED)
    output.invokeOnClose {
        one.cancel()
        two.cancel()
    }
    launch {
        var latestOne: E1 = one.receive()
        var latestTwo: E2 = two.receive()
        output.send(transform(latestOne, latestTwo))
        while (true) {
            select<Unit> {
                one.onReceive { latestOne = it }
                two.onReceive { latestTwo = it }
            }
            output.send(transform(latestOne, latestTwo))
        }
    }.invokeOnCompletion {
        one.cancel()
        two.cancel()
    }
    return output
}
(Edited to return
ReceiveChannel<T>
.) Do you think it's correct, especially regarding closing handling?
p

Paulius Ruminas

05/13/2019, 7:51 AM
If one or two channel gets cancelled
var latestOne: E1 = one.receive()
var latestTwo: E2 = two.receive()

select<Unit> {
        one.onReceive { latestOne = it }
        two.onReceive { latestTwo = it }
}
then these statements will throw
CancellationException
. Is this the behaviour you want?
l

louiscad

05/13/2019, 8:11 AM
Yes, that shouldn't be a problem since it'll be eaten by
launch
. I should cancel the two other channels though. I edited the snippet to return
ReceiveChannel<T>
BTW.
I also edited to cancel the channels on scope completion.
p

Paulius Ruminas

05/13/2019, 8:21 AM
Yes, that shouldn't be a problem since it'll be eaten by
launch
But it will cancel the whole scope if it is not
Supervised
.
runBlocking {
            val a = produce {
                while (true) {
                    delay(1_000)
                    send(1)
                }
            }
            val b = produce {
                while (true) {
                    delay(2_000)
                    send(2)
                }
            }

            coroutineScope {
                launch {
                    while (true) {
                        println("Test")
                        delay(1_000)
                    }
                }

                launch {
                    combineLatest(a, b) { a, b -> Pair(a, b) }.consumeEach {
                        println(it)
                    }
                }

                delay(10_000)
                a.cancel()
            }
        }
When
a.cancel()
is called it will throw an
Exception
and cancel the coroutine that prints "Test".
l

louiscad

05/13/2019, 8:25 AM
This:
runBlocking {
    launch {}.cancel()
}
doesn't throw because cancellation is not a crash, so it doesn't propagate to parent scope when the coroutine is concurrent (as with
launch
or
async
). So I don't see a problem here.
d

Dico

05/13/2019, 3:57 PM
@louiscad if one channel receives 2 items before the other receives any, does your solution drop the second item for the first channel? Depends on
onReceive
behaviour.
d

Dominaezzz

05/13/2019, 6:05 PM
If this is the only receiver, it doesn't.
l

louiscad

05/13/2019, 6:18 PM
@Dico The second value would not be received until the select is reached, and then, it'd be received immediately (unless the other channel has a value that is selected first because of bias), and would trigger a new transform and sending.