Skip to content

Instantly share code, notes, and snippets.

@jisungbin
Last active January 16, 2023 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jisungbin/4fb62cecc2f8e09eb7fa8516dfbabc06 to your computer and use it in GitHub Desktop.
Save jisungbin/4fb62cecc2f8e09eb7fa8516dfbabc06 to your computer and use it in GitHub Desktop.
fun <A, B> mutableStatePairOf(first: A, second: B): SnapshotMutablePair<A, B> {
return SnapshotMutablePairImpl(first, second)
}
fun <A, B> mutableStatePairOf(value: Pair<A, B>): SnapshotMutablePair<A, B> {
return SnapshotMutablePairImpl(value.first, value.second)
}
@Stable
interface SnapshotMutablePair<A, B> {
var value: Pair<A, B>
var first: A
var second: B
}
private class SnapshotMutablePairImpl<A, B>(
first: A,
second: B,
) : StateObject, SnapshotMutablePair<A, B> {
private var next = SnapshotPairRecord(first, second)
override var value: Pair<A, B>
get() = next.readable(this).asPair()
set(value) {
next.writable(this) {
first = value.first
second = value.second
}
}
override var first: A
get() = next.readable(this).first
set(value) {
next.writable(this) { first = value }
}
override var second: B
get() = next.readable(this).second
set(value) {
next.writable(this) { second = value }
}
override val firstStateRecord: StateRecord
get() = next
override fun prependStateRecord(value: StateRecord) {
@Suppress("UNCHECKED_CAST")
next = value as SnapshotPairRecord<A, B>
}
private class SnapshotPairRecord<A, B>(
var first: A,
var second: B,
) : StateRecord() {
override fun create(): StateRecord {
return SnapshotPairRecord(first, second)
}
override fun assign(value: StateRecord) {
@Suppress("UNCHECKED_CAST")
(value as SnapshotPairRecord<A, B>).let { record ->
first = record.first
second = record.second
}
}
fun asPair() = first to second
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment