Hi all. Trying to use interop with a pre-written `...
# compose
x
Hi all. Trying to use interop with a pre-written
RecyclerView
within a
@Composable
like this
Copy code
@Composable
fun ComposeRecyclerView(items: Items) {
  
  val adapter: RecyclerView.Adapter by remember { mutableStateOf( RecyclerView.Adapter()) }

  AndroidView(
    modifier = Modifier.fillMaxSize(),
    factory = { context -> RecyclerView(context) },
    update = { recyclerView ->
      if (recyclerView.adapter == null) {
        recyclerView.adapter = adapter
        recyclerView.adapter?.stateRestorationPolicy =
          RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
      }
  
      adapter.set(animatedState.items)
    }
  )
}
This doesn't seem to work. Is this the right way to use a legacy
RecyclerView
within Compose? Google is failing me because it keep showing me
LazyColumn
APIs which is not what I'm trying to achieve here 😅
👍 1
c
this looks correct, except you're not setting a layout manager for the recycler view? (And when I say correct, I mean, this would be how I'd attempt to do such a thing and not that it's actually correct 😂)
x
ah crap that was it 😅
thanks. I forgot how bad recycler APIs really were
c
I can't count how many times I've made the exact same mistake, good luck!
b
Does the adapter actually change? I don't think you need it in a mutable state, you could move it to the factory lambda.
Copy code
factory = { context -> RecyclerView(context).apply {
   val myAdapter = RecyclerView.Adapter()
   myAdapter..stateRestorationPolicy =        RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
   adapter = myAdapter
 }
Something like that
It would save that null check in update
x
I see, nah the adapter wasn't changing - I just needed a reference to my custom adapter by avoiding a cast of recycler.adapter.
b
One other note, if you just need to remember something to avoid reallocating it, no need for
mutableStateOf
. You can just do
remember { MyObject() }
x
Yup you are correct. This took me a while to wrap my head around. If i got this correctly -
State<T>
(from
remember { mutableStateOf() }
) helps to trigger recomposition when its state changes. However,
remember { YourObject }
just prevents reallocation when the
@Composable
function is executed multiple times
b
They are two distinct concepts.
remember
- caches objects across recompostion
mutableStateOf()
- creates a new mutable state. If you didn't remember your mutableStateOf, you would be creating a new mutable state on every recomposition