Views-Based Development vs Compose UI for Android Apps
Table of Contents

Views-Based Development vs Compose UI for Android Apps

Karlo Karagic
Senior Android Developer
Aleksander Jess
Content Marketer & Technical Expert

Declaratively building Android UIs

What does this phrase exactly mean? Well, luckily, we already spent too much time thinking about it and you can have a peek here. Long story short:  

It’s an abstraction layer built on top of the imperative style of UI. It does not concern itself with how to build the UI, but what you want to build.

Building UIs declaratively: UI is a function of state.

Declarative way of building UIs is the future, if it is not the standard already. You can see it on Android, iOS (Swift UI), the web (React), and desktop (React Native). It could be due to the state management approach and data immutability that comes with declarative UIs. While building declaratively you don’t change the UI; you rebuild it (in a controlled manner, of course).  

Imperative UI is more concerned with how to build something. This is the XML way. Not to get into too much detail, but you can define a TextView in there, then find it, and then tell it how it should look (setColor, setText, setFont etc…). The best way to explain is to look at the example below:

// Imperative - XML
val userTextView = view.findViewById<TextView>(R.id.userTv)
val name = "Some name"
with(userTextView) {
    text = name
    gravity = Gravity.CENTER
    setTypeface(Typeface.DEFAULT)
    if (name.length > 10) {
        setTextColor(R.color.red)
    } else {
        setTextColor(R.color.lightGreen)
    }
}

// Declarative - Compose
@Composable
fun UserText(userName: String) {
    val color = if (userName.length > 10) Color.Red else Color.Green
    Text(
        text = userName,
        fontFamily = FontFamily.Monospace,
        textAlign = TextAlign.Center
    )
}

Learning Curves

This is a hard aspect to reason about. The author of this article is working with Android (XML or not) for about seven years; therefore, all feels natural. But was it always so? No. Of course, not. Practice makes perfect. If you haven’t, we do recommend you check out this video with Jake Wharton and Saket Narayan.

Compose is something you can wrap your head around even if you don’t know Android. If you are coming from React, you are mostly missing Kotlin knowledge (more on that later). If you know Kotlin, Compose UI is just a natural extension of the language (XML is something completely different on the other hand). Even though you might know how to do things in the XML way, it is important to remember how many files you used to need for some simple UIs. Layers, shapes, border radiuses, layouts, custom views, attributes and so on. How hard could making a button with a border-radius be? This is the Android equivalent of centering a div for web developers.

Compose UI, on the other hand, is much simpler to get into. You can very quickly make a list of items (a lot of code was needed to do this with XML). You can easily create a semi-complicated screen on your first day. Learning the tech is an enjoyable experience, but there are some additional concepts to wrap your mind around, such as state management, coroutine integration and hoisting among others.  

Navigation  

With Compose, we can now also write some UI code for other platforms, especially the web. The web support had some negative consequences. What’s wrong? It feels more like JavaScript than Kotlin. We are essentially building URLs in Kotlin with String concatenation. With a type safe language like Kotlin, this feels wrong on so many levels.  

Let’s look at some code:

composable(
    route = "nextScreen/{arg_name}", 
    arguments = listOf(
        navArgument(arg_name) { type = NavType.StringType }
    )
) { entry ->
    SomeView(entry.arguments?.getString(arg_name))
}

The most important part in this example is in the route parameter. Notice how it looks like a URL, with the curly braces being what defines a navigation argument. First time one implements this, it’s easy to get it crashed because it's easy to forget how to define the dynamic part of the route.  

Your alternative options here are to make an in-house solution to address this issue, use a third-party library like this one, or wait and hope for the next update which will make this feature a viable option. Either way, this is suboptimal, to say the very least.

Is Compose UI Ready for production?

At the first glance Compose looks like a perfect tool we should all start to use immediately (and we mostly agree) but if you are a product owner of a large codebase you could remain a bit more conservative.

Every simple example of an app built with Compose UI looks extremely simple and intuitive, which may not be the case at scale. There are some projects hinting at a good project structure, but we will have to wait and see. When the number of app written with Compose UI increases, we’ll get a lot more feedback from the community on what works and what doesn’t.

With that being said, Compose UI is out of Beta for a year now, and it is a stable and safe to use. It does have an occasional bug and a quirk, but nothing major so far. As it is being pushed a lot (and is backed by Google) we presume that the situation will play out similarly as in the case of Java vs Kotlin. It's not a matter of if, but when.  

Another content piece, an article on betterprogramming.pub, that is also on the topic of maturity of the Android framework. There are some features missing from it as well as some features are behind a scary @ExperimentalApi annotation (it just means that the API may change at some point, but the feature is safe to use in this version). Luckily, almost immediately after publishing of that article, Compose 1.2 came out with new features or removal of experimental annotation. The development is still ongoing, and the improvements are fast, which is completely normal for such a new tool. To give you a safety net, developers working on Jetpack made sure you can use XML with compose if you must – interoperability with it works great.

There is potentially some overhead with Compose UI, or at least some unknowns. Check out this article, which made some big claims.  Compose UI’s performance is on par with XML performance but due to the JIT (Just in Time) compilation, the first load of the UI is 2.5x times slower after which it is only 60% slower (the difference is 60ms; one blink of an eye is 300 – 400ms long). There are some discussions on the code used in these tests, but the point is that it is still not 100% clear. What is clear is that XML is 12 years older than compose and, as such, has that many years of optimizations and improvements. Keep that in mind when you read the articles on this topic – what is true today may be outdated in a few months, and for sure outdated in a few years.

Developer Experience

With a declarative way of doing UI, we also get a bonus. All declarative UI tools tend to have similar concepts and logic behind them, which means the learning curve is flatter (no pun intended). You could have developers who can quickly grasp Android with Compose, iOS with Swift UI and web with React or Solid. It is not a realistic scenario, but it will surely help. According to Google, APK size and build speed is also affected by Compose. Especially the latter will impact developer satisfaction, as there is less time nervously waiting for builds to finish. This brings us to a feature which also helps with build or helps skip them - Preview. It is not always the best solution (hopefully it will improve) but it can help with faster iterations. We get a @Preview annotation, which renders the specific Composable element outside of the standard application build cycle.  

The next important thing to mention is the speed of development. Nobody likes to make the same screen for the tenth time, but you got to do what you got to do. Compose UI can help us here due to being a lot faster to write than XML both in the short and long term. A good example of this would be custom views. In XML, you need to implement a lot of boilerplate code - this is a problem because people become lazy and copy-paste code. With Compose, you just write your component and boom…custom view. Also, LazyColumn is the best, look how simple it is to make a Recycler View type list:

@Composable
fun list(list: List) {
    LazyColumn {
        items(list) {
            Text(it)
        }
    }
}

We simplified the code for the sake of this showcase - it all would be a more complex code in the real-world scenario, though. On the other hand, the way to set up Recycler View is a lot more complicated with a bunch more boilerplate (and an effortless way to introduce a memory leak if you don’t clear the adapter when you are done).

There are a few more examples we could provide here, but you get the gist of it. Every developer who tried the new tool felt they just dropped their chains. It is just a fun experience.  

What About Multiplatform?  

Compose brings with it a way to write web code in Kotlin. This is a good and a dreadful thing (TLDR - Navigation working for the web made the Native development experience worse). On a positive note, before, we had to pick either Android or Multiplatform. Now with Compose, we have something which seems natural for Kotlin developers to write the UI with for both.  

After you learn Compose, it is easier to write declarative code. This means that with Compose, Kotlin Multiplatform Mobile (next blog post, coming soon) and a little bit of Swift UI (really similar to Compose) you could be a one-man band on the Front-end.  

Check out these code blocks. It’s the same list of strings written in those 4 different frameworks:

@Composable
fun list(list: List) {
    LazyColumn {
        items(list) {
            Text(it)
        }
    }
}
// Vue
<div id="app">
  <ul>
    <li v-for="item in items">{{ item }}</li>
  </ul>
</div>

// React
export default function List(props) {
	const {items} = props
  return (
      <div>
           {items && items.map(item => <p>item</p>)}
      </div>
  )
}
func list(list: [IdentifiableString]) -> some View {
    List {
        ForEach (list) { element in
            Text(element.text)
        }
    }
}

Conclusion

Even though Compose is now one year stable, the author worked with it way before that. The author tried it a bit in Alpha, but that was not a pleasant experience, as the changes between versions made maintenance a living hell. The beta launched sometime in February 2021 that kicked it into gear. The author immediately jumped on it, this time more seriously.

Unfortunately, not everyone followed, which is why the use of the framework is limited in the professional setting. After making a few apps with it, you quickly grasp the concepts, and start having fun. Your development speed can only increase as you make your own “standard” library of components. Like we mentioned before, it does get a bit complicated when you get a bit into depth, but that is nothing too complicated (same concepts exist in any declarative UI framework).

What we are trying to say here is – just try it. Make a screen or two with it, create an About page in your app using it. Ask your team and colleagues to try it - they will be pleasantly surprised how easy it is to start and create something nice (also, animations are ridiculously simple). Happy coding!

Liked the article? subscribe to updates!
360° IT Check is a weekly publication where we bring you the latest and greatest in the world of tech. We cover topics like emerging technologies & frameworks, news about innovative startups, and other topics which affect the world of tech directly or indirectly.

Like what you’re reading? Make sure to subscribe to our weekly newsletter!
Categories:
Share

Join 17,850 tech enthusiasts for your weekly dose of tech news

By filling in the above fields and clicking “Subscribe”, you agree to the processing by ITMAGINATION of your personal data contained in the above form for the purposes of sending you messages in the form of newsletter subscription, in accordance with our Privacy Policy.
Thank you! Your submission has been received!
We will send you at most one email per week with our latest tech news and insights.

In the meantime, feel free to explore this page or our Resources page for eBooks, technical guides, GitHub Demos, and more!
Oops! Something went wrong while submitting the form.

Related articles

Our Partners & Certifications
Microsoft Gold Partner Certification 2021 for ITMAGINATION
AWS Partner Network ITMAGINATION
ISO 9001 ITMAGINATIONISO-IEC 27001:2013 ITMAGINATION
Great Place To Work
ITMAGINATION Winner Great Place To Work Best Workplaces Poland 2021
© 2022 ITMAGINATION. All Rights Reserved. Privacy Policy
// Opening all links in new tab // Syntax Highlighting Code