1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Snapshot.withMutableSnapshotでMutableStateをまとめて更新する

1
Last updated at Posted at 2026-11-19

Jetpack Compose で複数の MutableState を連続して更新する際には Snapshot.withMutableSnapshot を使ってまとめて更新することで、recomposition や snapshotFlow で中間状態の読み取りや競合を避けることができます。

実装例は以下です。

class TaskViewModel {
    var searchQuery by mutableStateOf("")
        private set

    var selectedTaskIds by mutableStateOf(emptySet<String>())
        private set

    fun updateSearchQuery(query: String) {
        Snapshot.withMutableSnapshot {
            searchQuery = query
            selectedTaskIds = emptySet()
        }
    }
}

注意点としては、異なるスレッドの withMutableSnapshot でまったく同じ MutableState を同時に書き換えた場合に競合エラーが発生します。その場合には Mutex で排他制御を行うか、mutableStateOf にカスタムの SnapshotMutationPolicy を渡すことで回避可能です。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?