u

    Utkarsh Tiwari

    1 year ago
    I have a composable A which I want to be allowed to be used only within composable B (kind of like make it internal to Composable B). Is there any way to achieve this?
    Here is my current code:
    @Composable
    fun ComposableB(
    content: @Composable LazyListScope.() -> Unit
    ) {
        LazyRow {     // edit
            content()
        }
    }
    
    @Composable
    fun LazyListScope.ComposableA() {
       val items = listOf(...)
    
       itemsIndexed(
            items = trimmedList,
            itemContent = { index, item ->
    
            }
        )
    }
    
    ComposableB {
    	ComposableA()  // Should only be allowed within this composable
    }
    Alex

    Alex

    1 year ago
    Well, you gave the answer yourself: Provide a scope object inside of your
    content
    method and make
    ComposableA()
    an extension function on that scope object. e.g. something like:
    object ComposableBScope
    
    @Composable
    fun ComposableBScope.ComposableA(){ ... }
    
    @Composable
    fun ComposableB(
    content: @Composable ComposableBScope.() -> Unit
    ) {
      content(ComposableBScope)
    }
    You could still call
    ComposableBScope.ComposableA()
    anywhere, but there are ways of restricting it more narrowly
    u

    Utkarsh Tiwari

    1 year ago
    Sorry, my code was incomplete. I just edited it. I thought of creating a custom scope but I still need the lazyListScope because ComposableB need a LazyRow to render items. I am not sure to how to keep both scope.
    Alex

    Alex

    1 year ago
    @Composable
    fun ComposableBScope.ComposableA(lazyListScope: LazyListScope) {
    You will get
    ComposableBScope
    as
    this
    and
    LazyListScope
    as
    it