Compose Tab without Hilt

SeongUg Steve Jung
2 min readJul 18, 2021

--

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?

In Multi Tab case, each tab will be able to have each own scope ViewModel.

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?

By other previous posting, We don’t use 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

Without Hilt and AAC ViewModel , We have to prepare how to provide ViewModel to each tabs structural. So we define a interface : ComposableHolder . It manages each tab’s DI injection and Composable function.

Appendex

You may question how to ComposableHolder has component. Let me put some example of Dagger components

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

--

--

SeongUg Steve Jung
SeongUg Steve Jung

Written by SeongUg Steve Jung

Android Developer, Google Developers Experts

Responses (3)