简体   繁体   中英

Composable getting bloated with too many callbacks passed

This is my current composable:

@Composable
fun MyComposable(
    onPress1: () -> Unit,
    onPress2: () -> Unit,
    onPress3: () -> Unit,
    onPress4: () -> Unit,
    onPress5: () -> Unit,
) {
    Button(onClick = onPress1) { Text(text = "Press 1")}
    Button(onClick = onPress2) { Text(text = "Press 2")}
    Button(onClick = onPress3) { Text(text = "Press 3")}
    Button(onClick = onPress4) { Text(text = "Press 4")}
    Button(onClick = onPress5) { Text(text = "Press 5")}
}

Is there a way to reduce this, Similar to how react has useReducer hook with action types and action payload

You can use sealed class to create click events that can be reused in different places in your project depending on your need.

// Create your different click events
sealed class MyClickEvent {
    object Press1: MyClickEvent()
    object Press2: MyClickEvent()
    object Press3: MyClickEvent()
    object Press4: MyClickEvent()
    // You can create a click event that passes arguments
    data class Press5(val arg: String): MyClickEvent()
}

// Handle each click event ( This function should be inside your view model )
fun onMyClickEvent(event: MyClickEvent) {
    when(event) {
        is MyClickEvent.Press1 -> println("Press1")
        is MyClickEvent.Press2 -> println("Press2")
        is MyClickEvent.Press3 -> println("Press3")
        is MyClickEvent.Press4 -> println("Press4")
        is MyClickEvent.Press5 -> println("Press5: ${event.arg}")
    }
}

@Composable
fun MyMainComposable() {
    MyComposable(
        onMyClickEvent = { event -> onMyClickEvent(event) }
    )
}

// Pass only single lambda for different click events
@Composable
fun MyComposable(
    onMyClickEvent: (event: MyClickEvent) -> Unit,
) {
    Button(onClick = { onMyClickEvent(MyClickEvent.Press1) }) {
        Text(text = "Press 1")
    }
    Button(onClick = { onMyClickEvent(MyClickEvent.Press2) }) {
        Text(text = "Press 2")
    }
    Button(onClick = { onMyClickEvent(MyClickEvent.Press3) }) {
        Text(text = "Press 3")
    }
    Button(onClick = { onMyClickEvent(MyClickEvent.Press4) }) {
        Text(text = "Press 4")
    }
    Button(onClick = { onMyClickEvent(MyClickEvent.Press5(arg = "data")) }) {
        Text(text = "Press 5")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM