I wrote a small composable that makes handling "is...
# compose
z
I wrote a small composable that makes handling "is this dialog visible?" pretty much seamlessly, without adding any extra overhead. Its very minimal, but I thought Id share it anyway; it has helped me tremendously! Code in thread 🧵
👍🏽 1
👍🏻 1
👍 2
This is how Id use it! No more
remember
and
if (showDialog) {}
, instead simply call
dialog.show()
or
dialog.dismiss()
.
Copy code
val dialog = rememberToggle { toggle ->
    Alert(
        onDismiss = {
            toggle.dismiss()
        },
        title = "I exist!"
    )
}
The code for the toggle is very minimal and mimics what happens when using remember, its just way easier to memorize how to use it.
Copy code
@Composable
inline fun rememberToggle(
    content: @Composable (Toggle) -> Unit
): Toggle {
    val toggle = remember {
        Toggle()
    }

    if (toggle.visible()) {
        content(toggle)
    }

    return toggle
}

@JvmInline
value class Toggle internal constructor(
    private val state: MutableState<Boolean>
) {

    private inline var visible
        get() = state.value
        set(value) {
            state.value = value
        }

    constructor(
        initialVisible: Boolean = false
    ) : this(
        state = mutableStateOf(initialVisible)
    )

    fun visible(): Boolean {
        return visible
    }

    fun show() {
        visible = true
    }

    fun dismiss() {
        visible = false
    }
}
m
A little remark. Maybe use “value class” is not good case here It designed for primitive types https://kotlinlang.org/docs/inline-classes.html
z
Correct me if Im wrong, but I dont think the type matters. The value/inline class simply makes it such that the resulting bytecode represents the underlying type, in this case the
Toggle
class becomes a
MutableState<Boolean>
u
This looks good nice one @Zoltan Demant 👍
👍🏽 1
c
I'm a little lost. What's the use case for this? I guess i never thought dialog handling was too verbose so maybe thats why I don't see the benefit. Not saying your wrong. just curious at motivation here. thanks!
z
@Colton Idle Its mostly the verbosity; with this I can create the toggle and declare the dialog it "controls" in the same spot. No need to declare the dialog elsewhere, and no need to check if it should be visible, all thats handled automatically for you.
👍 1