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
u

ursus

06/19/2019, 12:06 AM
Is there a way I can "connect" another callsite to a running coroutine? sort of like hot observable, where observer can join in on the receiving of the value produced
g

gildor

06/19/2019, 12:18 AM
You can use BroadcastChannel for this
u

ursus

06/19/2019, 12:24 AM
What about if you have params for that cooroutine? Youd need a key <-> param mapping, to get that Channel instance; most likely this should be a returned from the function, unless the caller chooses the id (key) but youll have different problems
and you cant just "anonymously" create that receiver, where for observables this would be hidden
g

gildor

06/19/2019, 12:29 AM
What do you mean about anonymous receiver?
u

ursus

06/19/2019, 12:30 AM
if the coroutine is parametrized, in order to get those values, youd need to get correct instance of channel
g

gildor

06/19/2019, 12:30 AM
Hard to say with this description, do you have some example, maybe, if you know how to do that, example of Rx implementation
u

ursus

06/19/2019, 12:30 AM
yes, second
private val someObservablesMap = hashMap<String, Observable<SomeResult>>

fun someObservable(someId: String) : Observable<SomeResult> {
	val obs = someObservable.getOrPut(someId) {
		Observable.fromCallable or whatever
	}
	return obs
}
callsite
someObservable("abc")
  .subscribe {}
or even better if the params is not a ID, just some data, and those are mapped into an id internally
g

gildor

06/19/2019, 12:33 AM
I don't see any connection here, you create observable which will be started again on subscription
u

ursus

06/19/2019, 12:33 AM
yes I omitted the hotness but okay ill add it in
class SomeManager {
	private val someObservablesMap = hashMap<String, Observable<SomeResult>>

	fun someObservable(someId: String) : Observable<SomeResult> {
		val obs = someObservable.getOrPut(someId) {
			Observable.fromCallable or whatever
				.refCount()
		}
		return obs
	}
}

call site

 someObservable("abc")
  .subscribe {}
g

gildor

06/19/2019, 12:34 AM
With coroutine it's even easier, if you need it one value, use HashMap<String, suspend () -> SomeResult>
Exactly, you not only omit that this coroutine is hot, but also it returns single value, so I really don't see why do you need Observable here
u

ursus

06/19/2019, 12:36 AM
im not saying I need observable, im researching coroutines and I know rx, and this is what Im missing
g

gildor

06/19/2019, 12:36 AM
It's hard to say what you want to do in this example, but if you just want to cache result of async operation you can just use Deffered
u

ursus

06/19/2019, 12:36 AM
because if you sideeffect to a Channel which isa different instance, how would you tell the caller the id of the channel to which it needs to subscribe to
g

gildor

06/19/2019, 12:37 AM
See, to convert this snippet to coroutines you don't need channel
u

ursus

06/19/2019, 12:38 AM
HashMap<String, suspend () -> SomeResult>
what would be that lamba? I dont follow
g

gildor

06/19/2019, 12:38 AM
Still not sure what you mean, what is your use case? Do you actually want to emit multiple events
This lambda is suspend function which replaces Observable.fromCallable
u

ursus

06/19/2019, 12:38 AM
No just one, my issue is scoping, say you have MessageManager.postMessage .. postMessage needs to complete regardless of if UI which triggered it is still there
g

gildor

06/19/2019, 12:39 AM
Because Observable.fromCallable is essentially the same as suspend lambda
u

ursus

06/19/2019, 12:39 AM
in Rx I'd do this via hot observables, and if UI comes back, it "reconnectes" to the same observable in order to get the return value
g

gildor

06/19/2019, 12:40 AM
But you cannot reconnect to cold Observable, like in your example
u

ursus

06/19/2019, 12:40 AM
my example is hot (refCount), I just forgot it sorry, I added it in the edited sample
g

gildor

06/19/2019, 12:40 AM
Hot observable in coroutines is Channel
For single value you don't need channel
u

ursus

06/19/2019, 12:41 AM
well yes but not really, since you need a way to grab the correct channel from the MessageManager; its an indirection, sideffecting of suspending function to the channel/relay
g

gildor

06/19/2019, 12:41 AM
Just use
async {}
it will just cache result in Deffered
u

ursus

06/19/2019, 12:42 AM
I dont think that will help, since, what if your UI instance goes away? How would you connect to the channel once it comes back (new UI instance)?
sec I'll write a sample
g

gildor

06/19/2019, 12:43 AM
You just call openSubscription() or asFlow() or call await() in case of Deferred
u

ursus

06/19/2019, 12:46 AM
I think you meant this
suspend fun postMessage(someText: String) {
	val requestUuid = createUuiFromText(someText)

	channels.getOrPut(requestUuid) { Channel() }
	// insert to database
	channels[requestUuid].send(State.SENDING)
	// apiClient.actuallySend
	channels[requestUuid].send(State.SENT)
}
my issue is, how would you let the callsite (ui) know about the requestUuid key, so it can grab the channel instance?
you need some sort of a channel of channels
whereas with hot observables Id just subscribe to the observable with same param and Id get the same instance from the hashmap
basically the parametrization of the postMessage is the core issue, you cannot just blindly MessageManager.stateChannel ..
g

gildor

06/19/2019, 1:14 AM
No, i don’t mean this
Quite similar implementation would be:
private val someObservablesMap = hashMap<String, BroadcastChannel<SomeResult>>

fun someChannel(someId: String) : ReceiveChannel<SomeResult> {
    val obs = someObservable.getOrPut(someId) {
        BroadcastChannel or whatever
    }
    return obs.openSubscription() // or asFlow() 
}

someChannel("abc")
  .consumeEach {}
This version don’t have
refcount()
feature to unsubscribe, only
publish()
to broadcast value
My main question is what
bservable.fromCallable or whatever.refCount()
should do
I mean you really want to unsubscribe if all subscribers are unsubscribed?
u

ursus

06/19/2019, 1:20 AM
ok Ill fill the body, sec
g

gildor

06/19/2019, 1:22 AM
If so, there is no such operator as refCount() in channel, there is proposal to provide connectable Flow abstractions: https://github.com/Kotlin/kotlinx.coroutines/issues/1086
u

ursus

06/19/2019, 1:24 AM
yes im aware of flow, im actually waiting for it; since as I said, flatmapping of singles is stupid, regular suspending functions is better and flow as replacement for Observables and im good
here is the body
class MessageManager {
    private val observablesMap = hashMap<String, Observable<Unit>>

    fun postMessageObservable(someText: String) : Observable<Unit> {
    	val key = sha1(someText)
        val obs = someObservable.getOrPut(key) {
            Observable.fromCallable {
            	// insert message to db with MessageState.SENDING
            	// apiClient.sendMessage(..)
            	// update message to db with MessageState.SENT
			}
            .publish()
            .autoConnect()
        }
        return obs
    }
}
I know that Observable.fromCallable is synchronous, it could be flatMaps of singles but whatever, doesnt matter for this example
g

gildor

06/19/2019, 1:25 AM
Observable.fromCallable {}.refCount()
is not valid code
You cannot refCount() Observable, only ConnectableObservable
u

ursus

06/19/2019, 1:26 AM
yes, sorry, im writing from memory
g

gildor

06/19/2019, 1:26 AM
Could you just explain semantics, how this should work
u

ursus

06/19/2019, 1:26 AM
I edited it, added the publish, changed it to autoconnect
okay so I want to post a message, its a MessageManager responsibility, and the posting action should be scoped to the MessageManager, meaning it should only be canceled, when MessageManager is closed -- and UI should just observe the result of this action, i.e. show some toast Message sent or whatever
UI can come and go ..its android, and postMessage should complete normalny, regardless of if UI is there, hence the publish.autoConnect
but if you come back to the same screen again (but different instance), you should be able to hook back in to the running postMessage observable, if its running and show the toast when finished
technically it should be Single not Obserable, but publish is not defined on Single
g

gildor

06/19/2019, 1:30 AM
publish is not defined on Single
Exactly
u

ursus

06/19/2019, 1:30 AM
but you can have observable tha only emits 1 and completes, nothing wrong with that
ist just semantics
g

gildor

06/19/2019, 1:35 AM
Isn’t you need something like this:
class MessageManager {
    private val observablesMap = hashMapOf<String, Deferred<Unit>>()

    fun postMessageObservable(someText: String) : Deferred<Unit> {
        val key = sha1(someText)
        val obs = observablesMap.getOrPut(key) {
            GlobalScope.async(start = CoroutineStart.LAZY) {
                // insert message to db with MessageState.SENDING
                // apiClient.sendMessage(..)
                // update message to db with MessageState.SENT
                Unit
            }
        }
        return obs
    }
}
Not so idiomatic (upd: after fix more idiomatic that version with observable), and you may have problems with not-thread same hashmap (but you already have it in your example)
u

ursus

06/19/2019, 1:37 AM
yes concurrent map but nevermind that
what would be the idiomatic way please?
g

gildor

06/19/2019, 1:37 AM
But semantically the same, it’s lazy, will be shared with multiple consumers and forever cache value
u

ursus

06/19/2019, 1:38 AM
suspend + sideffect to channel would be idiiomatic?
g

gildor

06/19/2019, 1:38 AM
sorry, I just now realized that you don’t need refCount() feature here, so you just start it once and cache forefere
no, this is most idiomatic way imo
you even don’t need Deferred
wait
u

ursus

06/19/2019, 1:38 AM
its pseudo code, yes youd clear the map in onFinally { observablesMap.remove(this) }
g

gildor

06/19/2019, 1:38 AM
Done:
class MessageManager {
    private val observablesMap = hashMapOf<String, Deferred<Unit>>()

    suspend fun postMessageObservable(someText: String) {
        val key = sha1(someText)
        val obs = observablesMap.getOrPut(key) {
            GlobalScope.async(start = CoroutineStart.LAZY) {
                // insert message to db with MessageState.SENDING
                // apiClient.sendMessage(..)
                // update message to db with MessageState.SENT

                Unit

            }
        }
        return obs.await()
    }
}
UPD: Careful with scope, GlobalScope here only for example
so no more streams, just suspending function to post message
u

ursus

06/19/2019, 1:40 AM
hmm nice, btw that would multicast in case I needed it or cant I have multiple subs to it?
g

gildor

06/19/2019, 1:40 AM
there is no subscription
you just suspend
u

ursus

06/19/2019, 1:41 AM
Id need a channel for that?
g

gildor

06/19/2019, 1:41 AM
you call it and receive result immidiately if message is delievered or suspend until it’s sending
no
because Observable with 1 element is just a suspend function
u

ursus

06/19/2019, 1:41 AM
I mean if multipleplaces need to know the result, id need some pipe like Subject / Channel I think?
yes, this is solved, im following up
g

gildor

06/19/2019, 1:41 AM
what I recommend to use in one of my first messages, but semantics of you code was not clear for me
mean if multipleplaces need to know the result
If you cache the same result, there is no problem, Deferred caches it
u

ursus

06/19/2019, 1:42 AM
no no you solved it with the last messge, im following up as how would you mutlicast this result to multiple places
Deffered is like a future?
Yes, Deffered is like a suspendable fututre
u

ursus

06/19/2019, 1:43 AM
kk thanks a lot
g

gildor

06/19/2019, 1:44 AM
But than you start using refCount() which semantics is quite different, it will not cache value forever, only while someone is subscribed
u

ursus

06/19/2019, 1:44 AM
btw do you have an opinion on the channel of channels?
or observable<observable<PostMessageState>>
g

gildor

06/19/2019, 1:44 AM
I would avoid it if I have better way, but probably sometimes it’s the only way
fun forceSync() {
    _state.offer(SyncStatus.SYNC)
    GlobalScope.launch {
      val result = if (load()) SyncStatus.IDLE else SyncStatus.FAILED
      _state.offer(result)
    }
  }
basically this
g

gildor

06/19/2019, 1:46 AM
Also, in my example there is GlobalScope, it’s just an example, most probably you need own scope for MessageManager
u

ursus

06/19/2019, 1:46 AM
but what if forceSync has some parameter, I dont know like Target.Foo, Target.Bar which it should sync
what would you do in this case please?
g

gildor

06/19/2019, 1:47 AM
What is Target.Foo? Anyway, I would start new thread instead, do not start new discussion here
u

ursus

06/19/2019, 1:48 AM
ok I will