https://kotlinlang.org logo
Title
z

Zoltan Demant

05/05/2022, 4:33 AM
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()
.
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.
@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

Max Novikov

05/05/2022, 7:23 AM
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

Zoltan Demant

05/05/2022, 8:00 AM
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

Umar Saidu

05/05/2022, 9:04 AM
This looks good nice one @Zoltan Demant 👍
👍🏽 1
c

Colton Idle

05/05/2022, 5:38 PM
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

Zoltan Demant

05/06/2022, 5:17 AM
@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