How to make a RecyclerView in Jetpack Compose — Part 1
Written as of alpha08. Compose is evolving rapidly so some syntax may have changed.
Edit — updated syntax with alpha09 changes
If you’ve developed for android you’ve inevitably come acrossRecyclerView
, it’s a massive improvement over ListView
which came before, but still pretty far from fun. Making a RecyclerView
involves a messy pile of boilerplate — often difficult to re-use between screens — and complexity even for basic tasks, like headers, item callbacks, and multiple item types.
How does Jetpack Compose make lists simpler?
Creating a list in compose
Creating a list in compose is ridiculously easy. No adapters. No view holders.
All you need is a defined data structure and composables to build list items. That’s really it. No joke.
Item click callbacks
Adding events to list items is also really simple with the use of kotlin lambdas.
Multiple item types
Jetpack Compose is data driven, so to have multiple item types we start with building the data structure —something which becomes common in compose world.
And when creating the list use a when statement to choose which composable to make depending on the data item.
With compose we can spend less time wiring the UI together and more time building attractive UI components backed by solid data structures.
Abstracting logic
What you might have noticed about the code samples above is that the view is really dumb.
Compose makes our view layer dumb by default. In old android you had to work to take logic out of the view layer and into the presentation layer — Presenters, ViewModels, etc — in Jetpack Compose you’d have to work to put logic into the view layer. Good architecture becomes the path of least resistance in compose world.
In compose the logic is all in the data structure and how we manipulate the data structure to display in the UI — the view is made of small re-usable components which react to changes in the data structure. This not only lets us move logic into higher levels of our app’s architecture with ease, it actively encourages it.
For lists, it makes our job ridiculously simple. But how does this work in reality? In the next post I take a look
https://ian-alexander.medium.com/how-to-make-a-recyclerview-in-compose-part-2-ef9309324f46
Happy composing!
For full samples see the repo here