Compose Tab without Hilt

Migration Rule 4 : Compose Navigation without Hilt and ViewModelProvider

In this posting, I will describe a trial how we implement Compose Tab without Hilt and AAC ViewModel.

You reading this post may think what matter is Compose, Hilt and AAC ViewModel.

Via Hilt and ViewModel Provider, we can inject ViewModel in Activity/Fragment easily.

In above snippet, MainActivity can get an injection of MainViewModel

In Compose, it also has a utility for ViewModel.

By hiltViewModel<VIEWMODEL>() , We can get MainViewModel instance simply.

So What?

Above code, while user has focused on foo tab, Composer is observing FooViewModel.title and it will dispose when user move to bar tab.

If a class is inherited from AAC ViewModel , Compose lever ViewModel injection easily.

What about not using AAC ViewModel and Hilt?

So we need to solve an issue.

We won’t inject and present all viewmodels in Activity/Fragment

Let’s imagine that there are 10+ tabs and each tab has 1~3 viewmodels.

To make simple above compose tab activity, I put ComposableHolder

inject() is for DI and render() is to render Compose View .

Tab screen will have each ComposableHolder

In MainActivity, it sets each ComposableHolder for tabs.

MainActivity has each tab’s ComposableHolder. The each ComposableHolder will present each tab’s screen and inject proper viewmodels.

Wrap up


Activity Component is @Component . And Each tab Component will be @SubComponent . In MainComponent , The module of component has a @Provides for holder. the function gets Builder of Component

Android Developer, Google Developers Experts