https://kotlinlang.org logo
Title
a

Aditya Wasan

02/01/2021, 6:05 AM
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
private val _isCacheReady = MutableStateFlow(false)
val isCacheReady = _isCacheReady.asStateFlow()
After filling up the cache, I'm updating the value
_isCacheReady.value = true
And here's the observing code
init {
  lobstersRepository.isCacheReady.onEach {
    _savedPosts.value = lobstersRepository.getAllPostsFromCache()
  }.launchIn(viewModelScope)
}
d

Dominaezzz

02/01/2021, 6:58 AM
Hmm, that looks fine. If you add `println`s in
onEach
, do they get printed?
a

Aditya Wasan

02/01/2021, 7:02 AM
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

Dominaezzz

02/01/2021, 7:19 AM
You're sure
_isCacheReady.value
set to true already?
a

Aditya Wasan

02/01/2021, 7:52 AM
Yep, tried logging the value of
_isCacheReady.value
after updating it.
d

Dominaezzz

02/01/2021, 8:09 AM
The first time
onEach
is called, is
it
true? (That's what I meant)
a

Aditya Wasan

02/01/2021, 10:33 AM
Oh sorry. Yeah it is false. I know MutableStateFlow won't re-emit the same state.
d

Dominaezzz

02/01/2021, 10:37 AM
Ah, I've got no idea then.
z

Zach Klippenstein (he/him) [MOD]

02/01/2021, 4:53 PM
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

Aditya Wasan

02/03/2021, 6:47 AM
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