dd-sdk-android icon indicating copy to clipboard operation
dd-sdk-android copied to clipboard

`trackClick` implementation for Composable `onClick` functions that take parameters

Open socksinbed opened this issue 2 years ago • 1 comments

Is your feature request related to a problem? Please describe. In the Compose SDK, com.datadog.android.compose.trackClick cannot be used for Composables that take an onClick with parameters, such as ClickableText which has a function signature:

@Composable
fun ClickableText(
    ...
    onClick: (Int) -> Unit
)

If we try to use it, there's a type mismatch:

@Composable
fun ClickableTextWithTrackedClicks(
    onClick: (Int) -> Unit
) {
    ClickableText(
        ...
        onClick = trackClick(targetName = "Test") { TODO() } // Type mismatch here, as (Int) -> Unit is expected
    )
}

Because trackClick is also a @Composable, it doesn't seem like there's a way to wrap it in a lambda. eg. If we wished to print the Int parameter

    ClickableText(
        ... 
        onClick = { i: Int ->
            println(i)
            trackClick(targetName = "Test") {}.invoke() // Can't be invoked because we're not in a `Composable` context
        }
    )

Describe the solution you'd like An implementation of trackClick that accepts a generically typed onClick lambda parameter such as:

@Composable
fun <T> trackClick(
    targetName: String,
    onClick: (T) -> Unit
): (T) -> Unit {
    val onTapState = rememberUpdatedState(newValue = onClick)
    return remember(targetName, attributes) {
        TapActionTracker(targetName, attributes, onTapState)
    }
}

// This will require a separate mplementation of TapActionTracker as well
internal class TapActionTracker<T>(
    private val targetName: String,
    private val attributes: Map<String, Any?> = emptyMap(),
    private val onTap: State<(T) -> Unit>,
    private val rumMonitor: RumMonitor = GlobalRum.get()
) : (T) -> Unit {

    override fun invoke(param: T) {
        // RUM code
        onTap.value.invoke(arg)
    }
}

socksinbed avatar May 02 '23 15:05 socksinbed

Hello @socksinbed! Thanks for reporting the issue, we will try to improve this API indeed.

0xnm avatar May 03 '23 06:05 0xnm