Kotlin DSL, BuildSrc, Product Flavors, Flavor Icon and more

For a long time, I wanted to migrate Gradle files to Kotlin DSL, but I was always procrastinating. I finally put an end to it and I also implemented buildSrc. It’s really important to check dependencies and versions. Especially in applications with more than one module, we can prevent different dependency management in each module with the buildSrc module.
Kotlin DSL 🤝 buildSrc

Let’s see, how we can do it?

What we will do in this article?

  1. refactor settings.gradle to settings.gradle.kts,
  2. create buildSrc package to project root directory,
  3. change .gradle files to .kts file,
  4. move versions and dependency strings to Kotlin files,
  5. extract keys from build.gradle and movekey.properties file,
  6. create product flavors and set configurations with Kotlin DSL.

The default project directory is like this:

1. Refactor settings.gradle to settings.gradle.kts

Rename settings.gradle file settings.gradle.kts and change a few code lines:

//before
rootProject.name = "KotlinDSL-BuildSrcExample"
include ':app'
// after
rootProject.name = "KotlinDSL-BuildSrcExample"
include(":app")

2. Create buildSrc package

Create “buildSrc” module to root project directory. And create build.gradle.kts file into it.

import org.gradle.kotlin.dsl.`kotlin-dsl`

plugins {
`kotlin-dsl`
}

repositories {
mavenCentral()
}

now rebuild project.

We have a buildSrc module. So, we can create Kotlin files in the module.

We will add Configs.kt,Versions.kt, Libraries.ktinto buildSrc/src//main/kotlin directory later.

3. refactor .gradle files to .kts file

We must change .gradle files to .gradle.kts. It’s the hardest part:

  • build.gradle(proje)

We use Kotlin in Gradle files. Let’s get the define Libraries.kt and Versions.kt Kotlin objects to buildSrc/src/main/kotlin

Hello Kotlin ✋

  • build.gradle(app module)

4. Move versions and dependency strings to Kotlin files

Now, we move out from defaultConfig to Configs.kt for app configs.

5. Extract keys from Gradle files (key.properties)

For more reliable codes, we must extract keys from Gradle and move another file like key.properties:

  • create key.properties file in the root project directory,
  • store keys (like signing keys) in this file,
  • create a helper class for getting the value of a key.
// build.gradle.kts (module :app)
signingConfigs {
create("signingConfigRelease") {
storeFile = file(KeyHelper.getValue(KeyHelper.KEY_STORE_FILE))
storePassword = KeyHelper.getValue(KeyHelper.KEY_STORE_PASS)
keyAlias = KeyHelper.getValue(KeyHelper.KEY_ALIAS)
keyPassword = KeyHelper.getValue(KeyHelper.KEY_PASS)
}
}
--------------------------------------------------------------------
// KeyHelper.kt
object KeyHelper {

const val KEY_STORE_FILE = "storeFile"
const val KEY_STORE_PASS = "storePassword"
const val KEY_ALIAS = "keyAlias"
const val KEY_PASS = "keyPassword"

private val properties by lazy {
Properties().apply { load(FileInputStream(File("key.properties"))) }
}

fun getValue(key: String): String {
return properties.getProperty(key)
}
}

6. Product Flavors and Configurations

Let’s create flavor together and set configurations with Kotlin DSL.

Create at least one flavorDimensions and your productFlavors. If you have environment specific value you can define in productFlavors:

flavorDimensions("appType")
productFlavors {
create("_dev") {
dimension = "appType"
applicationIdSuffix = ".dev"
versionNameSuffix = "-dev"

manifestPlaceholders(
mapOf(
"appIcon" to "@mipmap/ic_launcher_prod",
"appIconRound" to "@mipmap/ic_launcher_prod_round"
)
)
resValue("string", "app_name", "KotlinDslExample$versionNameSuffix")
buildConfigField("String", "ONESIGNAL_APP_ID", KeyHelper.KEY_ONESIGNAL_APP_ID_DEV)
}

In my case, besides the completely changed values, the change in base url was only in the extension part. And I handled it in the applicationVariants.all block.

And that’s all. I know it took a while, but I wanted to touch on the details. If you find any wrong info please leave a comment. I will fix it.

If this article helped you please press claps 👏

Resources

Project: https://github.com/mustafayigitt/KotlinDSL-BuildSrcExample

Linkedin: https://www.linkedin.com/in/mustafayigitt/

Website: https://www.mustafayigit.net/

Click 👏 to say “thanks!” and help others find this article.

To be up-to-date with great news on Kt. Academy, subscribe to the newsletter, observe Twitter and follow us on Medium.

If you need a Kotlin workshop, check how we can help you: kt.academy.


Kotlin DSL, BuildSrc, Product Flavors, Flavor Icon and more was originally published in Kt. Academy on Medium, where people are continuing the conversation by highlighting and responding to this story.

Continue ReadingKotlin DSL, BuildSrc, Product Flavors, Flavor Icon and more

Share your Gradle configuration with the Gradle Kotlin DSL — A guide for Android projects

Share your Gradle configuration with the Gradle Kotlin DSL — A guide for Android projects

This guide will help you to convert your Gradle build scripts from Groovy to Kotlin, allowing you to take advantage of some great benefits! These include:

  • Shareable Gradle configuration, minimizing the amount of duplicate code across your module build scripts
  • Shared dependency notation and versioning, making tasks like bumping dependency versions a breeze
  • Improved IDE support, enhancing features such as autocompletion, navigation to source, quick documentation, etc.

Step 1 – The buildSrc module

First, we will create a new directory at the root of our project named buildSrc. This is where all of our shared Gradle configuration, dependencies, versioning, etc. will live.

To make this directory a module we create a Kotlin build script at the root, so that the file path is {your_project}/buildSrc/build.gradle.kts

https://medium.com/media/96ca14688c6ebb508d27c60d7c2211b4/href

You should ensure that the versions used for com.android.tools.build:gradle and org.jetbrains.kotlin:kotlin-gradle-plugin match what you already have specified in your project build script ({your_project}/build.gradle) rather than using the versions in this example.

It’s also important to note the comments added to this file, it isn’t possible to utilise the shared versioning here so these dependencies will need to be updated manually.

Step 2 – Shared dependencies & versioning

It’s time to create the objects that will store our dependency notation and versioning, the process of moving all of your dependencies to these shared objects can be a bit painful depending on the number of dependencies your app uses.

Let’s start by creating the object that will hold our dependency notation. This should be created at {your_project}/buildSrc/src/main/kotlin/Dependencies.kt. I recommend going through your :app module’s build.gradle and copying any dependencies from there as a starting point.

I find it useful to group dependencies in nested objects as it increases readability, though you may structure this however you like. We can also group dependencies that are commonly included together using DependencyHandlerScope (you’ll see this in use later).

https://medium.com/media/15b390227cf6c356d7986d21b4b104e1/href

Now, let’s create the object that will house all of our versioning, create it alongside Dependencies at {your_project}/buildSrc/src/main/kotlin/Versions.kt.

As you can see, we’ve added all versions required by our dependencies, along with some versioning specific to our app in the nested App object.

https://medium.com/media/8cb1c4f7c663da91837c932d5080a7ff/href

I find it useful to also create a Modules object for storing module paths and a Plugins object for storing plugin identifiers to share even more values across build scripts!

https://medium.com/media/d199a3a76856389128c3b16c1ea457e6/hrefhttps://medium.com/media/b2a92abe9a4bc77069cec45e92d37a72/href

Step 3 – Converting app module build script to Kotlin

The steepest learning curve with the Gradle Kotlin DSL is the syntax. Below is an example Kotlin build script for the :app module which covers some common configuration, along with using our previously created Dependencies, Versions, Modules, and Plugins objects. If you have some complicated configuration that you’re struggling to convert, there are some links at the bottom of this guide to documentation that may help.

https://medium.com/media/138eceb26c5c19c2e79a2da1e778a20b/href

Step 4 – Shared module configuration

In my opinion, this is the greatest benefit of using the Gradle Kotlin DSL, the ability to easily share build script configuration across modules. First, let’s create a script that contains our shared configuration.

{your_project}/buildSrc/src/main/kotlin/common.gradle.kts

https://medium.com/media/22c734d091bf1ef32557b5c30df04bc9/href

Now we can utilise this to make module build scripts pithy by including common as a plugin!

https://medium.com/media/0071d30d46131f23961ce755fdb66679/href

Now you can go through each of your module build scripts and convert them to Kotlin, all whilst moving any dependencies, module paths, plugin identifiers, and versioning to the objects we created in step 2 so that they can be shared; allowing for easy alterations/updates in the future.

Step 5 – Converting project build script and settings.gradle to Kotlin

The final step is to convert your top-level (project) build.gradle and settings.gradle to Kotlin. This should be fairly straightforward as they won’t contain many configurations.

https://medium.com/media/2e4d9c296dd0a695da0a3c7a21354b15/hrefhttps://medium.com/media/f13cbe8ceeac3b56d8fb17772370041f/href

Fin

That’s it! 🎉 I hope this guide was useful and that you enjoy your new Gradle setup. All example code shown can be viewed in the example project linked below 🙂

MichaelM97/Gradle-Kotlin-DSL-Android-Example

Useful resources

Click 👏 to say “thanks!” and help others find this article.

To be up-to-date with great news on Kt. Academy, subscribe to the newsletter, observe Twitter and follow us on Medium.

If you need a Kotlin workshop, check how we can help you: kt.academy.


Share your Gradle configuration with the Gradle Kotlin DSL — A guide for Android projects was originally published in Kt. Academy on Medium, where people are continuing the conversation by highlighting and responding to this story.

Continue ReadingShare your Gradle configuration with the Gradle Kotlin DSL — A guide for Android projects

From Java to Kotlin in 20 minutes ⚡️

What is the experience like as a Java developer to start programming in Kotlin?

Credits: Katerine Salazar Gonzalez

What is the experience like as a Java developer to start programming in Kotlin?

I didn’t remember, it was years ago for me!

Fortunately, a mob-programming session with my colleagues gave me the chance to see again things with a beginner’s mind.

Show me the code!

To follow along, check out the code. You need to have IntelliJ Community Edition installed. It’s free! The code lives in the java and kotlin branches at https://github.com/jmfayard/from-java-to-kotlin. You can see all the changes described below in this pull-request

From Java to Kotlin by jmfayard · Pull Request #1 · jmfayard/from-java-to-kotlin

Let’s start by explaining the context of our story.

Mob-programming

My colleagues Sarah and Peter and I were doing a session of Mob programming.

The goal was to solve the kata of The observed PIN, where an unreliable spy tells that he saw the PIN 1357 being used. But actually, he’s not quite sure. Each digit could be one of its neighbors on the keyboard layout. So, the actual PIN could be 1357, but also for example 2357 or 1368.

The project was a Java project built with Maven. It contains two files: PinGuesser.java and PinGuesserTest.java. It compiles and runs the unit tests in a matter of seconds, not minutes, like in many Android apps. That makes for a better developer experience IMHO.

We were using IntelliJ’s Code With Me to write the code together.

We were doing well and have solved the Kata in Java, then refactored it to a satisfactory state.

  • Sarah: Is there anything else we could improve?
  • Peter: I don’t know, looks good to me.
  • Me: Well, we have 20 minutes left, why not rewriting the whole thing in Kotlin?
  • Sarah: Oh, I’ve heard about Kotlin but haven’t had the chance to use it yet. 20 minutes though, do you think we can do it?
  • Me: Let’s get started and see where it leads us!

Tools > Kotlin > Configure Kotlin in project

  • Peter: Ok, so I have never done any Kotlin in my life, tell me what to do.
  • Me: There is a command IntelliJ called Convert Java File to Kotlin File. It’s a great starting point!
  • Peter: Let’s give it a try.
  • Peter: IntelliJ tells me that Kotlin is not configured, that makes sense. How do I configure Kotlin in Maven?
  • Me: I don’t know, I’ve always used Gradle. Just let IntelliJ do it! By the way, what it will do is the same thing as Tools > Kotlin > Configure Kotlin in project.
  • Peter: Let’s do it…. It seems to have worked. There are updates to the file pom.xml.
  • Peter: first commit.

Tell Java that @ParametersAreNonnullByDefault

  • Me: Before we try the Java to Kotlin converter, there is something we want to take care of. As you know, Kotlin has integrated nullability in the type system while Java by default has not. Therefore, the converter is going to allow nulls everywhere, which is technically correct but not what you want.
  • Sarah: But there are annotations in Java to say if something is nullable or not, right?
  • Me: Exactly! And the one we want is to tell by default everything is non-null. Conveniently, it’s exactly how it works in Kotlin too.

https://medium.com/media/99627ac0574358fa44ac4a593276f40b/href

PinGuesser: Convert Java File to Kotlin File

  • Peter: I guess I now open PinGuesser.java and just relaunch the converter Convert Java File to Kotlin File .
  • Me: Correct.
  • Peter: It seems that… it worked? There is a file PinGuesser.kt.
  • Me: How do you know it worked, though?
  • Sarah: You should run the unit tests.
  • Peter: Right.
  • Peter: It’s still all green. Amazing, I have written my first Kotlin code ever, and it is bug-free!
  • Sarah: Good job!
  • Peter: What about the tests? Shouldn’t we convert those too?
  • Me: You don’t need to. Java and Kotlin can co-exist peacefully in the same codebase.
  • Sarah: Ok, but it looks fun, I want to try it out too!
  • Peter: First let me commit.

PinGuesserTest: Convert Java File to Kotlin File and manual fixes

  • Sarah: So I open PinGuesserTest.java and run the command. How is it called?
  • Peter: Convert Java File to Kotlin File .
  • Sarah: Let’s go! … I now have a PinGuesserTest.kt . It has some errors though.
  • Peter: Maybe apply the suggestion to optimize imports?
  • Sarah: Ok… It worked.
  • Me: As you see it’s not perfect, but it’s an awesome learning tool: you start with what you already know (in Java) and see it converted in what you want to learn (in Kotlin).
  • Sarah: Let me run the unit tests… I have some weird JUnit errors.
  • Me: Ok, so I understand that. Java has static methods while Kotlin has the concept of a companion object { … }. Its methods look like static methods but are a bit different. Here JUnit really wants static methods, and we need an annotation to make it happy.

https://medium.com/media/bc8ca0c6680c868f541cf148b9f4fad1/href

  • Sarah: Unit tests now work! The project is now 100% in Kotlin.
  • Sarah: commit.

Use the Kotlin standard library

  • Peter: What comes next?
  • Me: It’s possible to create List, Set and Map the traditional Java way, but the Kotlin standard library contains plenty of small utilities to streamline that, that would be my first change. Let me do it:
  • Me: That looks better. Are the unit tests still green?
  • Me: They are, let’s commit.

Replace stream() API with Kotlin stdlib

  • Me: Something else contained in the Kotlin Standard Library are functions found in the functional programming languages like .map(), .filter(), .flatmap() and much more.
  • Sarah: A bit like the Java Stream API that we are using?
  • Me: Yes, like this but less verbose and more performant under the hood.

https://medium.com/media/3e3dd35be9483c375fb28b1fc35a725e/href

  • Sarah: Unit tests are still green.
  • Sarah: commit.

Default to read-only properties

  • Me: Next, in idiomatic Kotlin style we tend to use val property instead of var property most of the time.
  • Peter: What’s the difference?
  • Me: val property is read-only, it has no setter, it’s like a final field in Java.
  • Peter: I see. So, I just change the var property with a val?
  • Me: Pretty much so.
  • Peter: Easy enough.
  • Peter: commit.

Fail fast

  • Sarah: Is there an idiomatic way to validate the parameters of a function? The PIN should be something like 7294 with all the characters being digits.
  • Me: Yes, you use require(condition) { “error message” } for that.
  • Sarah: How would that look here?

https://medium.com/media/62aa4889ee60c55477f1ba15f5338fb8/href

  • Sarah: Thanks!
  • Sarah: commit.

Functional style

  • Sarah: What comes next?
  • Me: I would like to liberate the functions.
  • Peter: What do you mean?
  • Me: Look, we have this PinGuesser class, but what is it doing exactly? It’s doing nothing, it’s a dumb namespace. It’s a noun that prevents us for accessing directly the verbs who are doing the real work. One of my favorite programming language of all time is Execution in the kingdom of nouns by Steve Yegge.
  • Sarah: I know that rant, pure genius ! So, how do we free up the verbs/functions?
  • Me: We remove the class and use top-level functions.

https://medium.com/media/7aec10545a227af1b465b1e95b90ed7f/href

List.fold()

  • Peter: Can we go a step back? What does it bring us to make the code nicer like this? At the end of the day, the customer doesn’t care.
  • Me: Well, I don’t know you, but I often don’t really understand the code I’m supposed to work on. I tend to work hard to simplify it and, at some point, it fits in my head and the solution becomes obvious.
  • Peter: What would it look like here?
  • Me: Now that the code is in a nice functional idiomatic Kotlin, I realize that the program can be solved using a single functional construct: List.fold().
  • Sarah: Show me the code.

https://medium.com/media/0e524b9762fbb7c381d57f0df7bd1d9c/href

And we are done

I hope that you liked this article.

If you want to get in touch, you are welcome to do so via https://jmfayard.dev/

The code is available at https://github.com/jmfayard/from-java-to-kotlin.

Start in the java branch and compare with what is the kotlin branch. See this pull-request.

If you are interested to learn more about Kotlin, I’ve written about it here.

How to learn Kotlin: browser vs IDE, books vs tutorials, for newbies and Java devs

Click 👏 to say “thanks!” and help others find this article.

To be up-to-date with great news on Kt. Academy, subscribe to the newsletter, observe Twitter and follow us on Medium.

If you need a Kotlin workshop, check how we can help you: kt.academy.


From Java to Kotlin in 20 minutes ⚡️ was originally published in Kt. Academy on Medium, where people are continuing the conversation by highlighting and responding to this story.

Continue ReadingFrom Java to Kotlin in 20 minutes ⚡️

Kotlin Multiplatform at HMRC

Hello, my name is George Herbert and I am a lead developer currently working as part of the HMRC Mobile App team. HMRC is the UK’s tax, payments, and customs authority. The app helps users to access their Help to Save accounts, manage their tax credits, and review their personal tax situation among other features. The team comprises iOS, Android, and backend developers. We encourage all developers to try other disciplines within the team, which gives us a reasonable level of cross-skilling. My role within the team is being the lead developer of the backend microservices.

About the HMRC App

The HMRC app has been in existence since 2012 and started off as a simple tax calculator. During 2016 the team undertook a rebuild by refining existing functionality, as well as adding the ability for users to login and manage their personal tax affairs, such as their Help to Save account or their tax credits. This means they do not have to ring HMRC or fill in any forms. Currently, we have half a million users a month, with users returning on average 7 times a month. The app is aimed at personal tax users and, when compared to the equivalent web services, it accounts for 50% of total traffic in the personal tax space. One of the app’s most popular and long-standing features is the tax calculator. The calculation logic for this is shared with the web. The web and the mobile calculator combine for 5.7 million visits a year of which the mobile accounts for 2 million of those.

From a Kotlin perspective, the Android team has been working gradually to migrate the app. At the time of writing, 86% of the app is now written in Kotlin

Use of Kotlin Multiplatform

Around 18 months ago my Tech Lead called a meeting to discuss the use of Kotlin Multiplatform (KMP), among other technologies, to help simplify and consolidate business logic within the apps and service. It was agreed that the HMRC Mobile App team, in partnership with Capgemini, would investigate this open-source product as a possibility within the app by starting simple and then going from there.

We wanted the user interface (UI) to be native as this was already built. We also felt building a core for business logic that could be shared, regardless of the choice of UI, would allow us to share this with the web more easily.

As mentioned, one of the main features in the app is the ability to calculate an estimate of your tax and take-home pay based on your salary, payment frequency and tax code. Updating the calculator every year required days of manual testing to ensure that everything worked as expected and had to be done for every platform! We identified this as an area that really needed an overhaul, to help with maintainability adding new tax bands each new tax year and reduce testing effort. The challenge was anything new still needed to support iOS, Android & web.

Screenshot of the HMRC app showing the resulting graph for take home salary and income tax for both Apple and Android
Results screen of the tax calculator within the HMRC App for iOS and Android

I am not an Android developer or even a Kotlin developer, my background is a Scala developer. I was keen to learn Kotlin and this seemed like a good opportunity. Within a couple of weeks, the tax-kalculator (see what we did there) was born: a Kotlin multiplatform library, with coverage of 98% and ready for use in the Android and iOS, and even the web version of the tax calculator. Adding new tax years now takes less than an hour and very minimal manual testing, thus saving us days of effort and time.

Over time, we have started to add other multiplatform aspects to the app such as a Help to Save calculator that will help forecast the amount of money you can save as part of the scheme. Going forward we are looking into more sophisticated uses for KMP that would help reduce duplication and improve the user experience across the platforms.

Getting to grips with KMP

As we began using KMP there were a few challenges we worked through as a team. The first was around setting the Gradle to support the platforms, as every example we looked at was slightly different and we were using Gradle.kts which was even more sparse when looking at an example. The issues around limited documentation, or outdated examples, is becomes less of a challenge as the popularity of KMP increases. Furthermore, as part of 1.4.0 the Gradle config has been simplified with the hierarchical project structure making this much easier and straight forward.

Man looking around for people in empty room
The struggle when looking for KMP examples, especially for gradle.kts

We faced a challenge with getting the framework for iOS in a state that could be consumed in our app without directly linking them in the Xcode build. One of the team’s iOS developers found a shell script that we added to our CI, that creates this and exports it to our GitHub. An example of this shell is on the repository for the project called package-ios.sh.

Finally, the iOS team faced the challenge of using multiple KMP projects in the same iOS app. This since been resolved in a newer version of KMP. As for the latter we temporarily (until the fix for this was added in 1.3.70) put all the KMP projects in one “super” library that contained all or KMP functionality just for iOS.

Summary

My advice is that if you want to try out KMP start small. For example, just write some business logic which is pure Kotlin and does not need platform-specific implementations, all the code should be in the commonMain. This makes the initial getting to grips with KMP simple as you don’t need to work with the actual and expects keywords. Once you are happy with the projects and their structures etc and they are working in your respective apps look to spread your wings into more challenging KMP (like consolidating your network logic and error handling for example).

I hope this has been interesting. If you have any questions about using KMP or either of our projects that are linked below, please feel free to message me on Twitter (@georgeherby).

Useful Links

HMRC KMP Libraries

Tax Kalculator

hmrc/tax-kalculator

Help to Save Kalculator

hmrc/help-to-save-kalculator

HMRC App

Play Store

HMRC – Apps on Google Play

App Store

‎HMRC

Something extra whilst your are here…

Recently the HMRC App team has open sourced its UI components for Android and iOS allowing anyone to build accessible apps with the same look and feel as the GOV.UK Design System.

Android Components

hmrc/android-components

iOS Components

hmrc/ios-components


Kotlin Multiplatform at HMRC was originally published in Kt. Academy on Medium, where people are continuing the conversation by highlighting and responding to this story.

Continue ReadingKotlin Multiplatform at HMRC

Jetpack Compose: First Impressions and Learning Resources

Android’s current UI toolkit is over 10 years old now… Do stop me if you’ve heard this before 😉

As you most certainly already know, Jetpack Compose is the hot new thing for Android UI development. Its promise is to save us by making all the pain points of the old View system and XML layouts go away.

After many many preview versions, it got to beta status about a week ago. Here’s what it’s like to use Compose at the moment, and some of the best places to learn more about it.

The good

First of all, Compose is exciting. It makes a lot of basic UI work really simple, and you get to write it all in Kotlin, making use of all the language’s powerful features! The APIs have great discoverability in Android Studio, since all of it is just Kotlin code that you can access via code completion. This makes it truly easy to get started.

Kotlin’s type safety also works wonders in Compose. No passing in dp values instead of pixels, or mixing up vertical and horizontal alignment options. Everything is strongly typed, and the compiler safeguards you from making many, many mistakes.

The declarative style and state management of Compose is great as well. Writing down what you want to appear based on state is not only clear and explicit, but also a blessing after the problematic state management of the View system.

Given how much effort is going into developing and marketing Compose, it’s almost certainly the future of Android UI development. That being said, the XML system will probably never fully go away. Just like the Java to Kotlin shift, it will take a couple years until the new standard really kicks in, and we’ll occasionally still find ourselves interacting with code from the before times.

So… Get on board soon, just don’t expect all of the old system to disappear overnight. I’d certainly still suggest learning the old XML based system to anyone starting Android Development today — unless they’re somehow very certain that they’ll never work on an existing project.

Jetpack Compose comes with some cool Android Studio tooling as well. Flutter users will probably already be familiar with the handy Surround with shortcuts that let you wrap pieces of code in a new widget, and the same makes an appearance in Studio now.

Select some code, invoke Surround with (Ctrl+Alt+J on Windows, ⌥⌘J on macOS), and then hit R for a Row, C for a Column, or W for an arbitrary widget.

Another quick tip: creating a new Composable will immediately add a parameter list and a body to it, and then place your cursor inside its parameter list, to let you immediately add modifiers and other parameters.

If you don’t want to add any parameters, you can hit Tab to quickly skip to defining its content.

The bad

Now, let’s see the bad part, continuing with the tooling theme. To run Compose, you’ll have to run the latest Canary version of Android Studio. This version has… Some issues.

From my personal experience of a few days:

  • IDE Previews (which would be a really nice feature for Compose) sometimes don’t load at all, or don’t update as changes are made (even after rebuilding). Re-running either the full app or just deploying a @Preview to a device was faster than using the IDE preview feature 100% of the time.
  • The debugger never connected to either an emulator or a physical device when running Compose apps. Still didn’t manage to solve this, though I heard others had more success.
  • Logcat doesn’t show app names when running apps, making it difficult to filter the logs for the current app.
  • When running the emulator in a tool window inside the IDE, the emulator tab occasionally doesn’t appear in the preview version of Studio. I had times when I used the emulator tab inside another project in a stable Android Studio instead… I eventually gave in and reverted to using an emulator in a separate window.
  • Sometimes Studio just froze up entirely, and its process had to be killed and restarted. This happened about once a day or so.

I heard some similar anecdotal stories from others, including excessive resource usage when using Compose compared to other projects. These were occasionally fixable by restarting, invalidating caches, restarting adb, and similar “usual” debugging practices.

Another pain point of using Jetpack Compose can be that looking up how to do things is a bit hit-and-miss for the time being. For example, when you land on StackOverflow questions about it, you’ll often find answers that say “this is how to do it in dev11”, or “here’s the new API for this in alpha3”, but then none of those APIs will be present in the current beta version.

Of course, on one hand it’s nice that Compose went through a lot of iteration and they weren’t afraid to change and evolve APIs — that’s what the preview versions are for.

On the other, it makes for a somewhat unpleasant experience for developers trying to build things on the latest Compose version. Thankfully this situation will naturally improve over time, but we’ll have to wait a bit to get enough new, up-to-date answers in.

The resources

Since StackOverflow won’t be your best friend for learning Compose yet, where else can you go?

First, there’s Google’s official resources, which are a decent start:

  • Their best resource by far is the written documentation pages — get started with them here. These include a lot of helpful explanation and snippets for designing things in Compose, and also touch on more advanced topics like navigation, architecture, and interop with existing code.
  • There’s a lot of video content about Compose as well, under the #AndroidShow branding. I’ll recommend skipping most of this, especially the livestream and Q&A parts — they’re not really developer-focused, and contain a lot of hype and marketing.
    What contains a lot of value, however, are their screencasts about Compose features (which are also included in sections of the written docs). You can find these in this YouTube playlist.
  • If you’re new to Compose, the Beta overview video is also worth watching. For more longer-form introductory content, these videos from last year are all really helpful: Jetpack Compose, Thinking in Compose, Compose by example, and Compose for existing apps.
  • For hands-on practice, take a look at Google’s Compose Pathway that includes videos, articles, and code labs. This goes into significant detail in some parts — feel free to skip the things you’re not interested in learning deeply immediately, otherwise it’ll take a long time to get through it.
    I also found that some of the codelabs here were outdated (not using beta1 APIs yet), so be prepared to fiddle a bit with the code snippets provided, or to debug dependencies. Again, this is something that will be improved soon.

If you prefer reading, RayWenderlich team’s Jetpack Compose book has really solid, professional content in it, providing a complete tour for you to get started with: A nice exploration of the basic UI building blocks of Compose, as well as multiple example apps. (This, again, is slightly outdated, as its samples use alpha10. Fingers crossed that it gets a revision soon.)

For even more long-form video explanations, guidance, and demos, Exploring Jetpack Compose and Advanced Jetpack Compose by Filip Babić are both excellent.

To find quick snippets for how to perform basic things, the Compose Academy site can come in handy.

Finally, exploring Compose on your own is also a great way to learn about it. All of the APIs you use are just Kotlin code, so exploring through code completion, and jumping into the underlying implementation in Android Studio to read the source are super easy. The in-code documentation for most Compose APIs also tends to be excellent.

Conclusion

Are you excited and ready for Jetpack Compose? We know that we are, and you can look forward to more Compose content from us soon, including in our Android Chat SDK.

Tweet at us @getstream_io and tell us what you think about Compose, and what you found to be the most useful way to learn about it!

Originally published at https://getstream.io.

Click 👏 to say “thanks!” and help others find this article.

To be up-to-date with great news on Kt. Academy, subscribe to the newsletter, observe Twitter and follow us on Medium.

If you need a Kotlin workshop, check how we can help you: kt.academy.


Jetpack Compose: First Impressions and Learning Resources was originally published in Kt. Academy on Medium, where people are continuing the conversation by highlighting and responding to this story.

Continue ReadingJetpack Compose: First Impressions and Learning Resources

End of content

No more pages to load