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?
Utkarsh Tiwari
04/12/2021, 1:42 PM
Here is my current code:
Copy 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
}
a
Alex
04/12/2021, 1:45 PM
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:
Copy code
object ComposableBScope
@Composable
fun ComposableBScope.ComposableA(){ ... }
@Composable
fun ComposableB(
content: @Composable ComposableBScope.() -> Unit
) {
content(ComposableBScope)
}
Alex
04/12/2021, 1:46 PM
You could still call
ComposableBScope.ComposableA()
anywhere, but there are ways of restricting it more narrowly
u
Utkarsh Tiwari
04/12/2021, 1:50 PM
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.
a
Alex
04/12/2021, 1:52 PM
Copy code
@Composable
fun ComposableBScope.ComposableA(lazyListScope: LazyListScope) {