https://kotlinlang.org logo
#compose
Title
# compose
a

Andrei Kovalev

10/20/2023, 12:54 PM
Hey folks, I’m trying to figure out if it is possible to migrate to
Modifier.Node
approach and get rid of
composed
modifier if I need to subscribe to a Flow and update modifier like this:
Copy code
override val modifier: Modifier = Modifier.composed {
        val value by flow.collectAsState()
        this.graphicsLayer {
            rotationX = value
        }
    }
Any suggestions are much appreciated, thanks!
a

Albert Chang

10/20/2023, 3:03 PM
This is it:
Copy code
private data class SomeModifierElement(
    private val flow: StateFlow<Float>
) : ModifierNodeElement<SomeModifierNode>() {

    override fun create(): SomeModifierNode =
        SomeModifierNode(flow)

    override fun update(node: SomeModifierNode) {
        node.updateFlow(flow)
    }
}

private class SomeModifierNode(
    flow: StateFlow<Float>
) : LayoutModifierNode, Modifier.Node() {

    private val flowOfFlow = MutableStateFlow(flow)
    private var value by mutableFloatStateOf(flow.value)

    fun updateFlow(flow: StateFlow<Float>) {
        flowOfFlow.value = flow
    }

    override fun onAttach() {
        coroutineScope.launch {
            flowOfFlow.collectLatest { flow ->
                flow.collect { value = it }
            }
        }
    }

    override fun MeasureScope.measure(measurable: Measurable, constraints: Constraints): MeasureResult {
        val placeable = measurable.measure(constraints)
        return layout(placeable.width, placeable.height) {
            placeable.placeWithLayer(0, 0) {
                rotationX = value
            }
        }
    }
}
a

Andrei Kovalev

10/20/2023, 3:05 PM
Thank you for your suggestion. Just realised there’s an easier way to do that if I can replace Flow with compose State I don’t actually need custom modifier
🎉 1
2 Views