https://kotlinlang.org logo
#arrow
Title
s

Sergey Shevtsov

06/21/2023, 11:40 AM
Hello! I have an immutable state with a map that looks like:
Copy code
@Immutable
@optics
data class ViewState(
  val someValue: Map<String, AnotherDataClass>
)

@Immutable
@optics
data class AnotherDataClass(
  val someList: List<String>
)
How can i change multiple values in this map in 1 operation using Arrow?
d

dave08

06/21/2023, 11:42 AM
s

Sergey Shevtsov

06/21/2023, 12:07 PM
I got something like this:
Copy code
@Immutable
@optics
data class ViewState(
  val key: SomeKey,
  val someValue: Map<SomeKey, AnotherDataClass>
)

enum class SomeKey { Key1, Key2 }

ViewState.someValue.every(Every.map).modify(state) { value ->
  val newList = when (value.key) {
    Key1 -> listOf(1, 2, 3)
    Key2 -> listOf(4, 5, 6)
  }
  AnotherDataClass.someList.set(value, newList)
}
This is fine? Or is there a better solution here?
d

dave08

06/21/2023, 12:10 PM
You tried optic's
copy { ... }
method on your ViewState?
There you can modify multiple elements in your data class in a clean way.
s

Sergey Shevtsov

06/21/2023, 12:33 PM
Take a look please. Is it good enough? I only need to change 2 lists for now
Copy code
private fun ViewState.setValues(list1: List<String>, list2: List<String>): ViewState = copy {
  ViewState.someValue.index(Index.map(), Key1).someList set list1
  ViewState.someValue.index(Index.map(), Key2).someList set list2
}
d

dave08

06/21/2023, 12:42 PM
Yeah, looks ok!
s

Sergey Shevtsov

06/21/2023, 12:44 PM
Thanks for the help! 🤜🤛
6 Views