Playing around with Feature Flags in Android (Kotlin)
Tags: android, kotlin, configcat, sdk
Published: 2022-01-25 09:47:54

Let's play with a hypothetical scenario where you've built a Kotlin-based mobile application, and you'd like to customize the overall user experience based on specified criteria. You've got a perfect idea, but then this question pops up everywhere: Now what? Folks, allow me to introduce you to the concept of feature flags in Kotlin.

<!--truncate-->

## Few words about feature flags 

A `feature flag`, also known as a feature toggle, is a technique that allows you to enable or disable different functionalities. As a product owner, you can toggle certain features on and off during the application's runtime. And because deploying mobile apps is not as straightforward as deploying web apps, when issues emerge in a mobile application, feature flags are a solution to avoid long app approval processes. 

My focus today will be on implementing ConfigCat's feature flags system in Android (Kotlin) using a sample mobile application. [ConfigCat](https://configcat.com/) provides [detailed documentation](https://configcat.com/docs/) on implementing feature flags in various technologies, including Java, Python, .NET and many others. Feel free to check the complete list [here](https://configcat.com/docs/sdk-reference/overview).

## Few words about the Android sample application  

For ease of reference, we'll be playing with a little [coffee shop app](https://github.com/mihaelapatrascu/DummyCoffeeShopApp) in this tutorial. Before you scare out, let me tell you it consists of just a few pages and a main menu screen. Put in other words, it's a simple mobile application that allows people to order beverages from a coffee shop. Easy-peasy, because I'm here to help.

### Why is it a good idea to use feature flags in an Android app? 

I'm a big fan of simplicity, so here's the rub. I plan to use a different version of the app's menu during the holiday season. Maybe change the theme, why not? Could be both, but either way, ConfigCat's feature management mechanism is here to help.

Let's stick to the special menu for now. I'll create and enable an oh-so-aptly called `Holiday` flag, which will:
 - adapt the menu with new, specific-to-the-special-season listings when the flag's value is 'true';  
 - make the app utilize its regular menu when the flag's value is 'false'. 
 
Note: To speed things along, I'll also occasionally peek at the [ConfigCat Android (Kotlin) SDK docs](https://configcat.com/docs/sdk-reference/android/).

## Prerequisites

Prior to coding, I ought to ensure that my app uses a [supported Android SDK version](https://configcat.com/docs/sdk-reference/android) (at least 18 in this case). Java 1.8 or above is likewise mandatory. The [`build.gradle`](https://github.com/mihaelapatrascu/DummyCoffeeShopApp/blob/master/app/build.gradle) file will advise me throughout the task.

```kotlin
compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
```

Furthermore, in terms of generating feature flags and deploying them in any application, you must have a ConfigCat account. So check out the [homepage](https://configcat.com/) and enroll. There is nothing to worry over, but if you get stuck, you can talk with the actual ConfigCat developers and acquire additional instructions [by heading over to Slack](https://configcat.com/slack/). I already have an account, therefore I'll skip this part. 

## How to connect an Android mobile app to ConfigCat?

The first step is to add the [ConfigCat Android (Kotlin) SDK](https://configcat.com/docs/sdk-reference/android/) into the project:

```kotlin
implementation 'com.configcat:configcat-android-client:6.+'
```

And import it wherever is needed:

```kotlin
import com.configcat.*
```

The ConfigCat SDK serves as the backbone of the overall feature flag system. You have to create your feature flags on the [ConfigCat Dashboard](https://app.configcat.com/) then the feature flag evaluation is done locally on the client-side in the SDK, therefore you don't have to wait for a request made to ConfigCat every time a feature flag `getValue()` is called, as the values are served from local cache. You can read about [polling modes and caching here](https://configcat.com/docs/sdk-reference/android/#polling-modes).

### The client and a special value

In this example, a single component will be implementing the feature flagging mechanism, but feel free to scale it and use it for your entire application. As I want to keep things straightforward for now, all I need is the `RecyclerView` located by the `home_fragment.xml` and its adaptor, the `RecyclerAdapter.kt` class. 

First, I ought to create a ConfigCat client:

```kotlin
val client = ConfigCatClient("#YOUR-SDK-KEY#")
```

Note: the placeholder `YOUR-SDK-KEY` ties the application with ConfigCat's service, so make sure you replace it with the uniquely-generated SDK key from your dashboard.

![dashboard-sdk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnjhiaea4w484qmnhzfh.jpg)
```kotlin
val sdk = holder.itemTitle.context.getString(R.string.sdk)
val client = ConfigCatClient(sdk)
```

Now that I've established my client, I need the `holiday` feature flag's value to assess the application's state: when the flag is `off`, the holiday season is over, and consumers may purchase usual specialties. I activate the festive menu otherwise.

There are several methods to get the flag's value, but for the sake of simplicity, I'll use the default mode with no user targeting. However, you can [read more about user targeting](https://configcat.com/docs/sdk-reference/android/#anatomy-of-getvalue) if you want to get different feature flag values for different users.

```kotlin
var holiday = client.getValue(Boolean::class.java, "holiday", false)
```
 
The `getValue` function will return the actual feature flag value, so it is called along with the feature flag's name and the default value. In the example above, the `holiday` variable holds the current flag’s value. The default value will be returned if the flag is not found or the local cache is empty.

### Last but not least

All that's left is to override the `onBindViewHolder` function (which is located in the `RecyclerAdapter.kt` class) depending on the feature flag value. If the value is true then the holiday menu is used, otherwise the standard menu is displayed. To achieve this, I use the lists below to change the menu’s regular layout.


```kotlin
if(holiday == true) {
    holder.itemTitle.text = titlesH[position]
    holder.itemIngredients.text = ingredientsH[position]
    holder.itemPrice.text = pricesH[position]
    Glide.with(holder.itemView)
        .load(imagesH[position])
        .into(holder.itemImage)
} else {
    holder.itemTitle.text = titles[position]
    holder.itemIngredients.text = ingredients[position]
    holder.itemPrice.text = prices[position]
    Glide.with(holder.itemView)
        .load(images[position])
        .into(holder.itemImage)
}
```

Whenever I toggle the holiday feature flag in my dashboard the menu items change accordingly. 

![toggle-menu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ta40kxatqkmx3e5h6hc.gif)

## Summary

Folks, let's recap the key steps in this tutorial:
- Create [a ConfigCat account](https://app.configcat.com/) if you don't have one yet.
- Install the [ConfigCat Android (Kotlin) SDK](https://configcat.com/docs/sdk-reference/android/) and create a client to link the app to the feature flags service.
- Implement your desired feature behind a feature flag.
- Toggle your feature on the ConfigCat Dashboard [https://app.configcat.com] anytime, even after publishing to the play store.
- Last but not least, make sure to follow [ConfigCat's guidelines](https://configcat.com/docs/sdk-reference/android/) for additional help.

## Learn more

- For more awesome articles on the feature flags topic, check out [ConfigCat's blog](https://configcat.com/blog/).
- Join ConfigCat on social media to keep in touch with the latest tech trends. Find ConfigCat on [Twitter](https://twitter.com/configcat), [Facebook](https://www.facebook.com/configcat), [LinkedIn](https://www.linkedin.com/company/configcat/) and [GitHub](https://github.com/configcat).
- Get [the sample app](https://github.com/mihaelapatrascu/DummyCoffeeShopApp) on GitHub.