Hide chapters

Real-World Android by Tutorials

First Edition · Android 10 · Kotlin 1.4 · AS 4

Section I: Developing Real World Apps

Section 1: 7 chapters
Show chapters Hide chapters

10. Building a Dynamic Feature
Written by Ricardo Costeira

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

The App Bundle publishing format is here to stay. Starting in the second half of 2021, Google Play will require you to publish new apps with the App Bundle format. Moreover, if your app’s size exceeds 150 MB, it must use either Play Feature Delivery or Play Asset Delivery.

This chapter assumes you’re aware of the theory behind dynamic features explained in Chapter 9, “Dynamic Features Theory”. Now, you’ll work on refactoring a common feature module and turning it into a dynamic feature.

Along the way, you’ll learn:

  • How to create an app bundle.
  • How to refactor a library module to a dynamic feature module.
  • How to navigate with dynamic features using the Navigation component.
  • How to inject dependencies into dynamic features.
  • How to test dynamic feature module installs.

You’ll focus on working with a new feature module that you’ll turn into a dynamic feature model that lets users install the feature only if they want to use it.

PetSave’s new features

The PetSave team has been hard at work, and the app has two updates. Open the starter project to check them out.

Start by expanding features. You’ll notice there’s a new feature module called sharing. This feature lets the user share a specific animal on their social networks.

Figure 10.1 — The Sharing Feature
Figure 10.1 — The Sharing Feature

The code is similar to onboarding’s, so if you’re familiar with that code already, there’s not much to gain in exploring the module.

You navigate to this screen through a deep link, thanks to the app’s other new feature. Go to the animalsnearyou module and expand presentation. You’ll find two packages inside:

  • main: Home to the code of the animals near you main screen, which you’re already familiar with.
  • animaldetails: Contains the code for a new screen that shows an animal’s details.

This screen appears when you click an animal in the list. It shows the animal’s name, picture and a few other details.

Figure 10.2 — Animal Details Screen
Figure 10.2 — Animal Details Screen

At the top-right corner of the screen is a share icon. Clicking it triggers the deep link into the sharing feature. The code behind it is similar to what you’ve seen so far, but there’s one difference worth noting: This screen uses sealed classes to handle the view state, making the view state that handles code in the Fragment similar to the event handling code in the ViewModel.

In the long term, both animals near you and search will use this screen. For now, however, you’ll handle it as if it’s part of animals near you for simplicity.

With the introductions out of the way, it’s time to get to work. You’ll refactor the sharing module into an on-demand dynamic feature module. With this change, only users who want that feature need to download it.

Deciding how to create your dynamic feature

To create a dynamic feature module, you have two options:

Preparing the app module

When using app bundles, you install the Gradle module defined as a first, so it makes sense to start from there. Typically, this is the app module.

implementation project(":features:animalsnearyou")
implementation project(":features:search")
implementation project(":features:onboarding")
implementation project(":features:sharing") // <- Remove
implementation project(":common")
implementation project(":logging")
dynamicFeatures = [":features:sharing"]

Managing dependencies

Go back to the dependencies tag. Since dynamic features depend on the app module, it’s a common practice to serve some of the common dynamic features dependencies through app. To do so, start by changing:

implementation project(":common")
implementation project(":logging")
api project(":common")
api project(":logging")
// Kotlin
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_android_version"

// Support Libraries and material
implementation "androidx.appcompat:appcompat:$appcompat_version"
implementation "$material_version"

// Navigation
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
// Kotlin
api "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_android_version"

// Support Libraries and material
api "androidx.appcompat:appcompat:$appcompat_version"
api "$material_version"

// Navigation
api "androidx.navigation:navigation-fragment-ktx:$nav_version"
api "androidx.navigation:navigation-ui-ktx:$nav_version"
api "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

Defining module names

When your app requests a dynamic feature, you usually ask the user to confirm that they want to install it. For that, you need the module’s name. Since you might need the module’s name before the user downloads it, you should define it in the base module as a string resource of up to 50 characters.

<string name="dynamic_feature_sharing_title">Share an animal</string>

Giving the app access to the dynamic features

Your last step is to enable access to dynamic feature code and resources on the app. To do this, enable SplitCompat.

class PetSaveApplication: SplitCompatApplication()
override fun attachBaseContext(base: Context) {

Figure 10.3 — Gradle Sync Error
Doyuva 43.2 — Tcazku Nhlx Ajhis

Preparing the feature module

Now, it’s time to refactor the sharing module. Start by opening its AndroidManifest.xml.

<dist:module // 1
  dist:instant="false" // 2
  dist:title="@string/dynamic_feature_sharing_title"> // 3
  <dist:delivery> // 4
    <dist:on-demand /> // 5
  <dist:fusing dist:include="true" /> // 6

Notifying Gradle about the dynamic feature

Locate the feature.sharing module’s build.gradle. Open it and delete everything inside. Then, add these lines at the top of the file:

apply plugin: ''
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: ''
android {
  compileSdkVersion rootProject.ext.compileSdkVersion

  defaultConfig {
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8

  kotlinOptions {
    jvmTarget = JavaVersion.VERSION_1_8.toString()

  buildFeatures {
    viewBinding true
dependencies {
  implementation project(':app')

  // Constraint Layout
  implementation "androidx.constraintlayout:constraintlayout:$constraint_layout_version"

  // UI
  implementation "com.github.bumptech.glide:glide:$glide_version"
  kapt "com.github.bumptech.glide:compiler:$glide_version"

  // DI
  implementation "$hilt_version"
  kapt "$hilt_version"
Figure 10.4 — Missing Navigation Definition
Nomiqi 35.5 — Hiswuxc Vehogejuen Qeguqukaiq

Figure 10.5 — Don’t Click the Share Button Yet!
Torako 02.8 — Wep’k Qkuxp xxi Wyugi Molwuz Ses!

Handling navigation

The Dynamic Navigator from the Navigation component library is just like the regular navigator. In fact, it’s an extension of the regular navigator, letting you navigate to dynamic feature modules just as you would to regular modules.

  app:defaultNavHost="true" />
private val navController by lazy {
  (supportFragmentManager.findFragmentById( as DynamicNavHostFragment)

Fixing the Share button

So far, you nested the nav_sharing graph into the nav_graph by including it there. Dynamic Navigator lets you do the same thing, but you need to use a different tag. You’ll include the sharing module to keep the code similar to how it was before. Note that Dynamic Navigator lets you navigate to a fragment tag, just as the normal navigator does.

  app:moduleName="sharing" />
  app:moduleName="sharing" />

Navigating between the animal details and sharing screens

First, you need to create the navigation action shown in the graph. Go to the animalsnearyou module and open nav_animalsnearyou.xml in res/navigation. In the fragment tag for AnimalDetailsFragment, below the argument tag already there, add this code:


    app:argType="long" />

Running the navigation action

Now, your last step is to run the navigation action in the code. Open AnimalDetailsFragment.kt in the animalsnearyou.presentation.animaldetails package of animalsnearyou. Build the app to generate the navigation directions. Then, locate navigateToSharing() and delete the code inside.

val animalId = requireArguments().getLong(ANIMAL_ID)

val directions = AnimalDetailsFragmentDirections.actionDetailsToSharing(animalId)


Handling dependency injection

Hilt doesn’t work well with dynamic features because of its monolithic component architecture.

interface SharingModuleDependencies

Declaring dependencies

So, which dependencies should you handle here? Declare these operations in the interface:

fun petFinderApi(): PetFinderApi
fun cache(): Cache
fun preferences(): Preferences
implementation "$dagger_version"
kapt "$dagger_version"

Bringing in Dagger

At the root of the sharing module, next to presentation, create a di package. Inside, create a file called SharingComponent.kt, with a SharingComponent interface inside.

@Component(dependencies = [SharingModuleDependencies::class])
interface SharingComponent
fun inject(fragment: SharingFragment) // 1

// 2
interface Builder {
  fun context(@BindsInstance context: Context): Builder
  fun moduleDependencies(sharingModuleDependencies: SharingModuleDependencies): Builder
  fun build(): SharingComponent
class SharingFragmentViewModel @Inject constructor
class SharingFragmentViewModel @Inject constructor

Preparing SharingFragment

In SharingFragment, above onCreateView(), override onCreate():

override fun onCreate(savedInstanceState: Bundle?) {


Using Dagger multibindings

To fix this, you’ll use Dagger multibindings to build a generic solution for ViewModel injection. In the di package you created just now, create ViewModelKey.kt. In it, add the following:

annotation class ViewModelKey(val value: KClass<out ViewModel>)
class ViewModelFactory @Inject constructor(
    private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {

  override fun <T : ViewModel> create(modelClass: Class<T>): T {
    var creator: Provider<out ViewModel>? = viewModels[modelClass]

    if (creator == null) {
      for ((key, value) in viewModels) {
        if (modelClass.isAssignableFrom(key)) {
          creator = value

    if (creator == null) {
      throw IllegalArgumentException("Unknown viewModel class $modelClass")

    try {
      return creator.get() as T
    } catch (e: Exception) {
      throw RuntimeException(e)

Binding the ViewModels

To bind the ViewModel instances, start by creating SharingModule.kt. In it, add SharingModule and annotate it with @Module:

abstract class SharingModule
// 1
@ViewModelKey(SharingFragmentViewModel::class) // 2
abstract fun bindSharingFragmentViewModel(
    sharingFragmentViewModel: SharingFragmentViewModel
): ViewModel

// 3
@Reusable // 4
abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory

Notifying SharingComponent of SharingModule

Open SharingComponent.kt and refactor the @Component annotation to:

    dependencies = [SharingModuleDependencies::class],
    modules = [SharingModule::class]
interface SharingComponent
lateinit var viewModelFactory: ViewModelFactory
private val viewModel by viewModels<SharingFragmentViewModel> { viewModelFactory }

Fixing errors

To do this, go to SharingModule.kt and add this annotation below @Module:

abstract fun bindDispatchersProvider(
    dispatchersProvider: CoroutineDispatchersProvider
): DispatchersProvider

abstract fun bindRepository(
    repository: PetFinderAnimalRepository
): AnimalRepository
Figure 10.6 — A Working Share Button!
Pexosa 18.1 — A Tesgunp Mjuxo Mifsef!

Testing module install

Android Studio installs all your modules by default, including dynamic features. You can edit the run/debug configuration and choose not to install dynamic features right away. Unfortunately, if you use this method, they won’t install later, either. For instance, choosing not to install the sharing module triggers this screen:

Figure 10.7 — Dynamic Navigator Handles Everything for You, Even the Failure Screen
Kugisa 35.2 — Gpmacuk Vepeyizih Sephqol Ajagxmqonl mov Dua, Axuh tdo Haenohi Pfweos

Preparing to use bundletool

Before using it, you need to create an App Bundle. A debug one will do.

Figure 10.8 — Building a Debug App Bundle
Cayare 88.5 — Yuenpunt a Daxev Akd Govydu

java -jar bundletool.jar build-apks --local-testing --bundle app-debug.aab --output app-debug.apks --connected-device
java -jar bundletool.jar install-apks --apks app-debug.apks
Pushed "/sdcard/Android/data/"
Pushed "/sdcard/Android/data/"
Pushed "/sdcard/Android/data/"
Pushed "/sdcard/Android/data/"
Pushed "/sdcard/Android/data/"
Figure 10.9 — Installing the Dynamic Feature
Xegoki 52.4 — Ufvlijwubv zje Sstexum Deilejo

Key points

  • The app module doesn’t depend on dynamic feature modules. However, you still have to make it aware of them through the dynamicFeatures array in its Gradle configuration.
  • Navigation component’s Dynamic Navigator does all the heavy lifting of requesting and installing dynamic features for you. It also handles network errors and even provides a basic installation progress Fragment.
  • You can continue to use Hilt in your app when you have dynamic feature modules. Hilt currently provides some basic functionality to inject bindings into dynamic features, but Dagger does most of the work.
  • bundletool is a great way of testing dynamic feature installation without having to publish your app on Google Play’s internal test track.

Where to go from here?

Great job on refactoring the module to a dynamic feature module. It took a lot of work, especially regarding Hilt/Dagger and navigation. Well done!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now