Hey guys, I have a question regarding MutableState...
# coroutines
a
Hey guys, I have a question regarding MutableStateFlow. I have a MutableStateFlow in my repo which is being observed in the ViewModel. However, the ViewModel is not receiving any updates. Here's the StateFlow that I have in my repository
Copy code
private val _isCacheReady = MutableStateFlow(false)
val isCacheReady = _isCacheReady.asStateFlow()
After filling up the cache, I'm updating the value
Copy code
_isCacheReady.value = true
And here's the observing code
Copy code
init {
  lobstersRepository.isCacheReady.onEach {
    _savedPosts.value = lobstersRepository.getAllPostsFromCache()
  }.launchIn(viewModelScope)
}
d
Hmm, that looks fine. If you add `println`s in
onEach
, do they get printed?
a
Yeah, so I've tried debugging everything and the
onEach
is called the first time when ViewModel initialises. However,
onEach
is not called again when I set
_isCacheReady.value = true
.
d
You're sure
_isCacheReady.value
set to true already?
a
Yep, tried logging the value of
_isCacheReady.value
after updating it.
d
The first time
onEach
is called, is
it
true? (That's what I meant)
a
Oh sorry. Yeah it is false. I know MutableStateFlow won't re-emit the same state.
d
Ah, I've got no idea then.
z
I’m not sure either, but just to confirm the basics – is the scope getting cancelled early for some reason? Add a
.onCompletion { println("complete: $it") }
before your
launchIn
☝️ 1
a
I don't think it should cancel because it is a viewmodel but I'll definitely check it.
Just tried it,
onCompletion {}
is called after the app is closed.
Here's the complete PR if anyone is interested in checking the app. https://github.com/msfjarvis/compose-lobsters/pull/101