Hi all Does anyone know why `StateFlow` doesn't em...
# announcements
m
Hi all Does anyone know why
StateFlow
doesn't emit new changes of a
MutableList
? this is my code:
Copy code
_selectedLanguages.value = _selectedLanguages.value.apply {
   if (changedLanguage.isSelected)
      add(changedLanguage)
   else
      remove(changedLanguage)
}
a
StateFlow
won't emit the same value. As you are setting the same list it won't be emitted. Use immutable list instead.
Or if you want to stick with
MutableList
, use
MutableSharedFlow(replay = 1,onBufferOverflow = BufferOverflow.DROP_OLDEST)
.
m
The value of stateFlow is mutableList cause i want to change it on runtime, I checked mutablelist's hashcode doesn't change when I add to or remove from it
I'll try the MutableSharedFlow, thanks for helping.
g
mutablelist’s hashcode is changing on content change
if you list is ArrayList
a
m
@gildor I've tried the code below but it doesn't
hashCode
too:
Copy code
val a = arrayListOf(1,,2, 3)
val b = a
b.add(4)
println(a==b) // prints true
g
yep, exactly
@Mjahangiry75 It’;s not hashcode! It’s equals! it’s not the same
also problem here of course that you comparing 2 the same objects, so this solution: flow.value = flow.value.mutate() Will never work in this case, because when it will be compared, it will be the same object (of course with the same content)
m
@gildor yes, why does it equals when I added an item to it?
g
because flow.value and your changed lis is the same object
so when you add something, value in flow.value already there, it has reference to the same object
you can just copy list and it will work: flow.value = flow.value.toMutableList().mutate()
m
Thanks men @gildor @Albert Chang, I'm trying your solutions.
@gildor it works like a charm!!!!. you saved my day.
g
in general it doesn’t look as good solution to have mutable list in your Flow
instead I would make it read-only
so it would allow you just do:
Copy code
_selectedLanguages.value = if (changedLanguage.isSelected)
      _selectedLanguages.value + changedLanguage
   else
      _selectedLanguages.value - changedLanguage
}
m
Yes, you are right!
z
Also FYI there’s a #C1CFAFJSK channel
m
@Zach Klippenstein (he/him) [MOD] In my case in need it as a stateflow to use in databinding Thanks for information
z
This question comes up a lot, so I filed https://github.com/Kotlin/kotlinx.coroutines/issues/2516
👍 1
m
Good job.