https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

Marc Knaup

10/14/2020, 1:14 PM
MutableStateFlow
is great for passing around a shared cache, or is it? 🤔
l

louiscad

10/14/2020, 1:15 PM
Beware of race conditions on update, but yes.
👍 1
m

Marc Knaup

10/14/2020, 1:17 PM
Oh, wait. That way if I update the cache I immediately receive the update myself again. That’s not good 😅
l

louiscad

10/14/2020, 1:18 PM
Better to wrap the cache in a domain specific API
m

Marc Knaup

10/14/2020, 1:18 PM
Makes sense
I still have a cycle. Whenever I save to the cache I also receive the same value as an update. I will need some logic so that whoever updates the cache doesn’t receive the same value back 🤔
Maybe something crazy like:
Copy code
fun <T> MutableStateFlow<T>.withoutEmittingValueChanges(): MutableStateFlow<T> = …
It returns a new
MutableStateFlow
that only emits values if they were not set by that Flow itself.
c

Casey Brooks

10/14/2020, 2:11 PM
I woudln’t say it’s necessarily an issue that whoever sets a value also gets an updates; it helps ensure that the UI is actually reacting to changes in that cache rather than making ad-hoc updates on its own.
m

Marc Knaup

10/14/2020, 2:13 PM
It is if it’s recursive. My flow: 1. Collect data from cache 2. On cache data change, start updating data from API using the cached data as initial data 3. Send new data to cache That’s an endless loop
No UI here
The problem is that the emission of values that will be cached depends on initial value supplied by the same cache
Here’s my actual code that would now have that problem
I’ve posted in the wrong channel. Solution I’m working on: https://gist.github.com/fluidsonic/a06419b1c129f3045558c63cbafecca4
4 Views