🤖

Jetpack Compose 老害に「キミはもう少しエレガントに書けないかね」と言われた Switch()

2022/07/05に公開

何をもって「エレガント」とか言っちゃってるのか。

どれが「エレガント」ですかね。

すべて動作は確認済み。

■ 近くで State を持つ

var checked by remember { mutableStateOf(false) }

Switch(
  checked = checked,
  onCheckedChange = { value ->
    checked = value
  }
)
var checked: Boolean by remember { mutableStateOf(false) }

Switch(
  checked = checked,
  onCheckedChange = {
    checked = !checked
  }
)
var checked by remember { mutableStateOf(false) }
val onCheckedChange = { value: Boolean ->  checked = value }

Switch(
  checked = checked,
  onCheckedChange = onCheckedChange
)
var checked by remember { mutableStateOf(false) }
val onCheckedChange = { _: Boolean -> checked = !checked }

Switch(
  checked = checked,
  onCheckedChange = onCheckedChange
)

■ ViewModel で State を持つ

PokeViewModel

@HiltViewModel
class PokeViewModel @Inject constructor() : ViewModel() {

  private val _switchState: MutableState<Boolean> = mutableStateOf(false)
  val switchState: State<Boolean>
    get() = _switchState

  fun update(value: Boolean) {
    _switchState.value = value
  }
  
}

PokeScreen Switch()

Switch(
  checked = viewModel.switchState.value,
  onCheckedChange = { value: Boolean -> viewModel.update(value) }
)
val checked by viewModel.switchState
val onCheckedChange = { value: Boolean -> viewModel.update(value) }

Switch(
  checked = checked,
  onCheckedChange = onCheckedChange
)  
val checked by viewModel.switchState
val onCheckedChange = { value: Boolean -> viewModel.update(value) }

Switch(
  checked = checked,
  onCheckedChange = onCheckedChange
)
val checked by viewModel.switchState

Switch(
  checked = checked,
  onCheckedChange = { viewModel.update(!checked) }
)
val checked by viewModel.switchState
val onCheckedChange = { _: Boolean -> viewModel.update(!checked) }

Switch(
  checked = checked,
  onCheckedChange = onCheckedChange
)

■ まとめ

シンプルに見えれば「エレガント」なんだろ? な?

👉 【Jetpack Compose】 NavBackStackEntry - Composable のライフサイクルと ViewModel の状態を確認する

Discussion