Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.handstandsam.mutablestateflow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Test
class UseImmutableDataWithMutableStateFlow {
data class SomePojo(var name: String = "placeholder")
@Test
fun testMutableDataIsBad() = runBlockingTest {
val somePojo = SomePojo()
val mutableStateFlow = MutableStateFlow(somePojo)
println("INITIAL: ${mutableStateFlow.value}")
// Update the value
somePojo.name = "Something Different"
// Assign the new value to the MutableStateFlow
println("CURRENT: ${mutableStateFlow.value}")
mutableStateFlow.value = somePojo
println("UPDATED: ${mutableStateFlow.value}")
// It's the same object you already modified and therefore the value is the same,
// and no emission will occur from the MutableStateFlow
}
}
INITIAL: SomePojo(name=placeholder)
CURRENT: SomePojo(name=Something Different)
UPDATED: SomePojo(name=Something Different)
@norrisboat
Copy link

norrisboat commented May 28, 2021

Thanks very much for this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment