Peter Mandeljc

    Peter Mandeljc

    1 year ago
    would it be a bad idea, to have a CompositionLocalProvider for a callback, to communicate with root composable, like post msg on a msg bus?
    typealias Callback = (String) -> Unit
    
    // Fixme: composition policy
    val LocalActiveCallback = compositionLocalOf<Callback> { error("No active callback") }
    
    @Composable
    @Preview
    fun Parent() {
        val callback: Callback = { msg ->
            Timber.e(msg)
        }
    
        CompositionLocalProvider(LocalActiveCallback provides callback) {
            Child()
        }
    }
    
    @Composable
    private fun Child() {
        val callback = LocalActiveCallback.current
    
        Button(onClick = {
            callback("hello")
        }) {
            Text("call me")
        }
    }
    Csaba Kozák

    Csaba Kozák

    1 year ago
    I also used this technique to communicate from a tab screen to the root screen, as i needed to animate the bottom nav according to some state in a very deep composable function. I would try to avoid this as possible, still it is working in my case.
    K Merle

    K Merle

    1 year ago
    It looks super handy indeed. My main concern is testing, after that, hiding implementations. It could get very hard to debug I would imagine if app gets big.