Native operations for MutableStateFlow

I have a structure:

data class Foo(
    val max: Int,
    val current: Int
)
val foo = MutableStateFlow(Foo (10, 0))

Then I need to make some math operations:

with(foo) {
  value = value.copy(current = value.current + 5)
}

Is it possible to simplify this code to value += 5? Because of its verbosity, I think maybe I should change the Foo class to something like:

data class Foo(
    val max: MutableStateFlow<Int> = MutableStateFlow(0),
    val current: MutableStateFlow<Int> = MutableStateFlow(0)
)
val foo = Foo(MutableStateFlow(10), MutableStateFlow(0))

Kotlin doesn’t know how to add integer to Foo. You need to implement an operator:

operator fun Foo.plus(value: Int) = copy(current = current + value)

Then foo.value += 5 will work as you expect.

2 Likes

That looks useful. Sadly, only 1 parameter is possible to determine this way. And it acts like the whole class is incremented.

Yeah, it’s still inconvenient with many params. And it looks tough when you override setter
(foo.value = 5).

Is it possible to implement MutableStateFlow inside? Something like:

data class Foo(
  var max: Int,
  var current: Int
){
  fun mutable() = MutableStateFlow(Counter(max, current))
}

Maybe even add private and setters for enough encapsulation and reactivity.

As I understand, making less StateFlows reduces calculations, so, it’s better to have only 1 update on the whole data class. But how much performance do we save? Does it have a kind of pre-calculations of all necessary vars before @Composable updates?

That is a future possibility we entertain with better support for value classes. See the discussion of this exactly use-case here: KEEP/value-classes.md at master · Kotlin/KEEP · GitHub

1 Like