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
o

Orhan Tozan

04/04/2020, 12:07 PM
I'm trying to do something like the following:
fun messagesFromConversation(conversationId: String): Flow<List<Message>> = channelFlow {
    val messageHistory = getMessageHistory()
    offer(messageHistory)
    val accumulatedMessages = messageHistory.toMutableList()
    val sentMessages: Flow<Message> = sentMessagesFromConversation(conversationId)
    sentMessages.collect { sentMessage ->
        acumulatedMessages.add(0, sentMessage)
        offer(accumulatedMessages)
    }
}
but Im getting a weird issue that on every collect of the sentmessages, the accumulatedmessages are not represeting the full list. I think it's some sort of mutable state sharing concurrency issue, but I have no idea how to better approach this issue. Do I need to some sort of ConcurrentMutableList?
m

Marc Knaup

04/04/2020, 12:09 PM
offer
may return
false
if an element wasn’t accepted due to the channel being busy. Did you mean to use
send
?
Interestingly I’ve written something very similar a few days ago. Also conversations and messages. But I exclusively use immutable list and create copies to ensure that I never have shared mutable state.
If something subscribes to your flow holds a long-lived reference to the list, it may get surprised that the list content has suddenly changed.
send(accumulatedMessages.toList())
+ the other
offer
->
send
o

Orhan Tozan

04/04/2020, 12:19 PM
offer is not returning false, also, looks like the issue isnt with the channelflow emitting, but updating the mutable messages list. For example, given the message history is two messages, when the sent message flow emits another message, I breakpoint and I get the following state from the debugger: accumulatedmessages.size = 3. But when after lets say 10 seconds the next sent message gets emitted, when I breakpoint it, the accumulatedmessage.size is back to 2, as of the previous sentmessage didnt happen. Now the previous send chat message appears after some emits after, but its really unstable.
m

Marc Knaup

04/04/2020, 12:20 PM
Are you sure it’s still the same flow? I.e. has
this
changed between breakpoints?
o

Orhan Tozan

04/04/2020, 12:21 PM
@Marc Knaup wow thats really great you also did this, helps alot. I have to tell you, I initially also tried this with immutability, but then you have the following immutability right:
var accumulatedMessages
m

Marc Knaup

04/04/2020, 12:21 PM
yes, but that immutability isn’t shared
o

Orhan Tozan

04/04/2020, 12:21 PM
I got the same issue, I was even using ImmutableList and PersistentList from this library:
m

Marc Knaup

04/04/2020, 12:22 PM
Some
println
may also help here. Maybe multiple flows are created instead of one. There should be no need for special immutable lists if you only send copies around 🙂
Here’s a random example of my code. Note the
listOf(message) + snapshot.queue
to create a new immutable list instead of mutating any existing one.
o

Orhan Tozan

04/04/2020, 12:25 PM
Thanks for the help because it drives me crazy. So do you suggest something like this:?
var accumulatedMessages: List<Message> = messageHistory
sentMessages.collect { sentMessage ->
    accumulatedMessages = accumulatedMessages + sentMessage
    send(accumulatedMessages)
}
I have to to also tell you, this is not the exact full code. In the same channelFlow, Im also collecting incomingMessages, also a flow. So they are both collecting in their own coroutine. Is it still a good idea then to use send isntead of offer()?
m

Marc Knaup

04/04/2020, 12:27 PM
If you have two
collect
in your flow and both are never-ending streams then the second
collect
should never be called because the first will run forever?
o

Orhan Tozan

04/04/2020, 12:28 PM
Do you mind if I post the whole code here?
m

Marc Knaup

04/04/2020, 12:28 PM
A Gist may be easier to read
o

Orhan Tozan

04/04/2020, 12:30 PM
I never used Gist, so I put it in a pastebin instead: https://pastebin.com/M16fisXQ
As an answer to your question, you can see all of the collects get launched in the scope of the channelFLow
So they all collect in their own coroutine
m

Marc Knaup

04/04/2020, 12:33 PM
In any case I guess all these
offer
should be
send
. Any reason you’ve used
offer
?
o

Orhan Tozan

04/04/2020, 12:34 PM
I saw offer being used alot in channelFLow examples, and I thought if send is suspending, it might block the other collecting flows, but I just realised that they are all running in their own coroutine ofcourse, so it wont be a problem
However, I remember also trying send() and it not making a difference. The emitting part is also not the issue, its that the accumulatedlist doesnt seem to get persisted
m

Marc Knaup

04/04/2020, 12:35 PM
Well
offer
is okay if you are okay with some elements never being sent in certain situations. But I guess that isn’t okay here 🙂
o

Orhan Tozan

04/04/2020, 12:35 PM
I might as well not use offer and send() at all, and just see how the sent messages dont get persisteted directly to the list
Yes, I will change it to send()
But now posting this pastebin has me realised with the following: all of their collects are being run in their own coroutine, and im not using awaitClose at the end, meaning the channelflow probably hit the end. Do you think that might trouble?
m

Marc Knaup

04/04/2020, 12:36 PM
Oh, there’s a
conflate
at the end. That may make it irrelevant whether to use
offer
or
send
because with
conflate
the buffer is never full 🤔
o

Orhan Tozan

04/04/2020, 12:37 PM
Right, I thought conflate() was a good thing here since all that iss important is the latest state of the messages
Anyhow the bug was also there before using conflate()
m

Marc Knaup

04/04/2020, 12:38 PM
Yeah. I just usually leave the decision up to the consumer. Anyway, not the cause
o

Orhan Tozan

04/04/2020, 12:39 PM
yes, its either conflate() for emitter, or collectLatest for receiver right
Anyway, would this be better you think:?
accumulatedMessages = accumulatedMessages + sentMessage
send(accumulatedMessages)
m

Marc Knaup

04/04/2020, 12:39 PM
Probably not. I guess the issue lies somewhere else
o

Orhan Tozan

04/04/2020, 12:46 PM
Perhaps I need to put awaitClose at the end of the channelflow to keep it running, even tho I have no idea how that can correlate with this persisting issue
m

Marc Knaup

04/04/2020, 12:48 PM
Since you don’t even use
awaitClose
you may as well just use
flow { … }
? It should stay open automatically though.
Can you put a
println
at the start of the flow? Just to make sure that we’re only observing a single flow.
o

Orhan Tozan

04/04/2020, 12:49 PM
When I was using flow {} I got an illegalstateexception sometihng with flow invariant and emitting from different coroutine, and that I had to use channelFlow instead
Just for your information: incomingmessages gets also generated by a channelflow
m

Marc Knaup

04/04/2020, 12:49 PM
So you did a workaround instead of understanding the problem. Maybe it tried to tell you where the concurrency issue lies 😄
o

Orhan Tozan

04/04/2020, 12:50 PM
I will try it again using flow {} and share the exception
Also, wait, if I use flow, I can't collect in parallel
}.launchIn(this) wouldn't work since this wouldnt be a CoroutineScope then
m

Marc Knaup

04/04/2020, 12:52 PM
I think you have to wrap the entire flow content in a
coroutineScope { … }
o

Orhan Tozan

04/04/2020, 12:52 PM
Allright, will do
Also thought of that, but I remember that exception occuring from there
But lets give it another try
m

Marc Knaup

04/04/2020, 12:53 PM
yeah that may make sense. not sure if that’s compatible with flow
I’ve just tested it.
flow {}
and
coroutineScope {}
work just fine together.
o

Orhan Tozan

04/04/2020, 12:55 PM
I think it depends on what you are doing inside of the coroutineScope
m

Marc Knaup

04/04/2020, 12:56 PM
Yeah,
flow {}
and
launch {}
don’t seem to work together.
o

Orhan Tozan

04/04/2020, 12:56 PM
W/System.err: java.lang.IllegalStateException: Flow invariant is violated:
    		Emission from another coroutine is detected.
    		Child of StandaloneCoroutine{Active}@f625a8a, expected child of StandaloneCoroutine{Active}@532c8fb.
    		FlowCollector is not thread-safe and concurrent emissions are prohibited.
    		To mitigate this restriction please use 'channelFlow' builder instead of 'flow'
W/System.err: java.lang.IllegalStateException: Flow invariant is violated:
    		Emission from another coroutine is detected.
    		Child of StandaloneCoroutine{Active}@f625a8a, expected child of StandaloneCoroutine{Active}@532c8fb.
    		FlowCollector is not thread-safe and concurrent emissions are prohibited.
    		To mitigate this restriction please use 'channelFlow' builder instead of 'flow'
Concurrent emissions are prohibited it says
m

Marc Knaup

04/04/2020, 12:57 PM
Well there is a way around. But I’m not sure if it’s the proper way 😄
You can save the context outside:
val flowContext = coroutineContext
and then use it inside:
withContext(flowContext) {
   emit(…)
}
o

Orhan Tozan

04/04/2020, 12:59 PM
I dont know if thats recommended: since at the end of the exception it also says to use:
FlowCollector is not thread-safe and concurrent emissions are prohibited.
    		To mitigate this restriction please use 'channelFlow' builder instead of 'flow'
m

Marc Knaup

04/04/2020, 1:01 PM
It says that the approach you’re using isn’t thread-safe. If you use
channelFlow
you’ve silenced the warning but you code must also be thread-safe then. But it isn’t due to mutable state.
o

Orhan Tozan

04/04/2020, 1:01 PM
Maybe I have some useful information to share
the
sentChatMessages
flow is coming from here, outside of the class as a private field
one moment
private val _sentOneOnOneChatMessages: Channel<OneOnOneChatMessage<ChatMessageContent>> = Channel()
    private val sentChatMessages: Flow<OneOnOneChatMessage<ChatMessageContent>> =
        _sentOneOnOneChatMessages.receiveAsFlow()
And here is where that channel gets its messages from:
Only relevant line of the last picture is the last one, the
also {}
so the sentChatMessagesFlow is a hot flow
Perhaps using BroadcastChannel is a better fit there than Channel
m

Marc Knaup

04/04/2020, 1:15 PM
I’d try this in all `onEach`:
withContext(flowContext) {
   // on each code (including mutable state access)
}
to have all code within the Flow run in the same context
The launch causes a thread switch
otoh that should’t be an issue
ugh, it’s complicated 😄
(Have you checked that the flow isn’t collected multiple times?)
o

Orhan Tozan

04/04/2020, 1:19 PM
Yes, the breakpoint only gets hit once at the start
m

Marc Knaup

04/04/2020, 1:19 PM
good
o

Orhan Tozan

04/04/2020, 1:20 PM
I don't get why the launch would cause a thread switch from collecting the sent messages
launching a coroutine simply inherits the context right? So that means that the coroutine is already running in the flow context
m

Marc Knaup

04/04/2020, 1:21 PM
It gets its own context because launching creates a new
Job
.
I’m still puzzled because of your error description.
Creates an instance of the cold Flow with elements that are sent to a SendChannel provided to the builder's block of code via ProducerScope. It allows elements to be produced by code that is running in a different context or concurrently. The resulting flow is cold, which means that block is called every time a terminal operator is applied to the resulting flow.
m

Marc Knaup

04/04/2020, 1:23 PM
You say the message list becomes shorter again, which is impossible if it’s still the same flow. There is no way the list can get shorter except for starting a new flow?!
o

Orhan Tozan

04/04/2020, 1:24 PM
I'm not trusting the debugger
I think im just gonna bust out printlns everywhere
m

Marc Knaup

04/04/2020, 1:25 PM
hehe, good old prints
still, put one at the start please :)
o

Orhan Tozan

04/04/2020, 1:25 PM
yep, going to do
Will come back with the result in ~10 mins
Thank you for helping, its hard to find some real word usecases with Flow
m

Marc Knaup

04/04/2020, 1:30 PM
Takes a while to think in Flows, yes. And I keep hitting limits 😄
o

Orhan Tozan

04/04/2020, 1:50 PM
PENTAGON: channelFlow start PENTAGON: channelFlow start PENTAGON: channelFlow end PENTAGON: channelFlow end PENTAGON: sentChatMessages.onEach start PENTAGON: sentChatMessages.onEach currentChatMessages.size=21 PENTAGON: adding sentChatMessage, content=Text(value=2) PENTAGON: sending: currentChatMessages.size=22 PENTAGON: sentChatMessages.onEach end PENTAGON: sentChatMessages.onEach start PENTAGON: sentChatMessages.onEach currentChatMessages.size=21 PENTAGON: adding sentChatMessage, content=Text(value=3) PENTAGON: sending: currentChatMessages.size=22 PENTAGON: sentChatMessages.onEach end PENTAGON: sentChatMessages.onEach start PENTAGON: sentChatMessages.onEach currentChatMessages.size=22 PENTAGON: adding sentChatMessage, content=Text(value=testtest) PENTAGON: sending: currentChatMessages.size=23 PENTAGON: sentChatMessages.onEach end
m

Marc Knaup

04/04/2020, 1:50 PM
How can it end when it’s still emitting? Where exactly did you print start & end?
o

Orhan Tozan

04/04/2020, 1:51 PM
You see, when sentmessage with content 2 is being added (2 is the actual message body), the message list size was together 22. now when the next sent message came in, the list became 21 again
m

Marc Knaup

04/04/2020, 1:52 PM
But you have two flows running. How do you know what log message is what flow instance?
o

Orhan Tozan

04/04/2020, 1:53 PM
I updated the output log again, check how on the 3rd message, the message size is back to 22
you mean the two channelFlows at the start?
m

Marc Knaup

04/04/2020, 1:53 PM
yes
o

Orhan Tozan

04/04/2020, 1:53 PM
Yes I dont know where that one comes from, im only using this flow once
Maybe thats the issue
m

Marc Knaup

04/04/2020, 1:54 PM
yeah, likely 🙂
o

Orhan Tozan

04/04/2020, 1:54 PM
But have no idea how
Im going to put out some more printlns from the caller, will report back
Allright, the code you saw till know was from the repo. The viewmodel calls an usecase, which calls the repo. Just found out the usecases flow also gets called twice
PENTAGON: usecase channelflow start PENTAGON: usecase channelflow start PENTAGON: channelFlow start PENTAGON: channelFlow start PENTAGON: channelFlow end PENTAGON: channelFlow end
Looks like something is going wrong with the viewmodel
Yep omg
Fixed it
m

Marc Knaup

04/04/2020, 2:02 PM
😄
o

Orhan Tozan

04/04/2020, 2:02 PM
Looks like the issue was a small innocent but righteous evil wrong use of
asLiveData()
on Flow
I forgot that asLiveData() starts a collect
It was being collected twice from the viewmodel
m

Marc Knaup

04/04/2020, 2:04 PM
I try to avoid
LiveData
if possible. Not sure though if Kotlin covers all use cases yet 🤔
o

Orhan Tozan

04/04/2020, 2:05 PM
I will show you what I was trying to do
I commented the only relevant lines with
// RELEVANT
You can see the line on 115 was the evil one
I guess in order to do what I want to do, is using the share() operator thats still in draft
m

Marc Knaup

04/04/2020, 2:10 PM
I have merged the entire conversation state into a
ConversationContentSnapshot
. It includes messages, send queue, loading states, errors, etc. But my UI is still imperative so I just collect all snapshots and save the latest one in a property in the presenter.
o

Orhan Tozan

04/04/2020, 2:14 PM
Yes, I guess I need to use that too.
m

Marc Knaup

04/04/2020, 2:16 PM
Status quo, in case it helps with thinking :)
o

Orhan Tozan

04/04/2020, 2:18 PM
Indeed, I have something like this