Server Driven UI in Jetpack Compose (SDUI)
Did you know that you can simply define the state of your UI from the server side easily by using Jetpack Compose in Android?
Let's first explore a simple scenario where data is retrieved from the server using Ktor or Retrofit or whatever the framework you prefer for fetching data from apis:
Steps taken:
If the data consumed has the following structure:
data class Book(
val bookName: String,
val author: String,
val blaBlaBla: AnyType
)
Until now no magic in the traditional flow most of us take to consume data from api, now what if view state is added to the fetched data or even fetching some view state from an independent endpoint provided?
For example what if the following is retrieved:
Recommended by LinkedIn
data class BookWithViewState(
val bookName: String,
val author: String,
val blaBlaBla: AnyType,
val viewState: ViewState
)
ViewState is an enum class or whatever which could be one of the following ViewStateOne, ViewStateTwo, .... etc
The flow is the same to fetch the data (a little bit modified if view states are fetched independently), the thing that will be added is step 6 where the ui component to be shown is defined based on the view state fetched from the api.
for example in the ui you can add the following:
@Composable
fun SomeComposable(myBooks: List<MyBookWithViewState>){
LazyColum...{
....
when (item.viewState) {
ViewStateOne-> ShowFirstComposable(
item = item
)
ViewStateTwo-> ShowSecondComposable(
item = item
)
}
...
}
Now, you have unlimited number of ways to play with this, you can easily add textSize, fonts, shapes ... or whatever you want or need.
Example Projects from Github: