Search code examples
androidankokotlin-extensionandroid-ktx

Android KTX or Anko


I'm a little confused about the advantages and disadvantages of using Android KTX vs Anko. Because both libraries are trying to achieve the same end goal, and the line between them it's getting a little bit blurry to the point, in some cases, the same functionality is available in both libraries.

I will be very thankful if you help me to clarify the mission of each one, and their use cases.

Thanks in advance!


Solution

  • Anko is a project JetBrains started while developing Kotlin and making it relevant for Android. I'd qualify it as an early production-ready showcase of Kotlin possibilities.

    Anko is well known for Anko layouts, but also has some extensions for Android development in Anko Commons, and also a few other modules like SQLite.

    However, Anko libraries have accumulated a significant number of methods updates after updates, which today make the library relatively heavyweight when you are limited to 65K methods per dex file (I prefer staying with a single one, for apk size and performance reasons).

    Anko commons provides extensions for Android, so it's similar to Android KTX in a way, but it's not as well integrated and organized (packages and artifacts wise) as Android KTX which is now part of AndroidX, which is part of Android Jetpack. Making the libraries smaller, and more loosely coupled is part of the Android Jetpack / Android X philosophy BTW.

    So Android KTX, is clearly the future, and I see no reason to not jump in the ship, or rather, not letting it jump in your Android projects.

    Also, as you yourself pointed out, future Anko versions will deprecate (and probably finally remove) overlap with Android KTX, to provide only features that are not in AndroidX.

    Includes a shameless plug: Since you're talking about Anko, if Anko layouts got your attention, but you experienced struggles with them (especially when interacting with custom or third-party views), I'd recommend you to check out Views DSL in Splitties, which is more flexible than Anko layouts, and very lightweight. The other modules may also interest you. I started this project to leverage Kotlin features in my Android projects at work and at home.

    You've not asked about it, but here's my take on Anko coroutines: I find the bg { … } extension confusing. I prefer to use kotlinx.coroutines with the Android artifact, using launch, withContext, etc, along with Dispatchers.IO.

    However, the Anko coroutines listeners (e.g. onClick that can suspend) are not a bad idea IMO.