How to update data of a RecyclerView that is inside a composable function?

I have a RecyclerView that is created and added to my compose layout through the AndroidView function.

@Composable
fun MyView(data: State<List<Item>>) {
   ...
   AndroidView(factory = { context ->
        RecyclerView(context).apply {
            layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
            layoutManager = LinearLayoutManager(context)
            adapter = ItemListAdapter().also { it.submitList(data.value) }
        }
    })
}

I used RecyclerView instead of LazyColumn because I want to have add and remove animations which is not yet supported by LazyColumn and I achieve that with the RecyclerView through the use of DiffUtil

Now, every time my data changes, the view is recomposed, thus the RecyclerView is recreated and the animations are not showed.

What is the best way in which I can achieve this? Should I just pass a LiveData then observe it on the RecyclerView’s Adapter?

Thanks

Answer

Use update callback, it gets called on each recomposition:

AndroidView(
    factory = { context ->
        RecyclerView(context).apply {
            layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
            layoutManager = LinearLayoutManager(context)
            adapter = ItemListAdapter().also { it.submitList().value }
        }
    },
    update = { recyclerView ->

    }
)

Not sure why you’re saying that “RecyclerView is recreated” on each recomposition, it shouldn’t be like that. I’ve tested and only update = { gets called on recomposition