分類
發燒車訊

Android官方新推的DI庫 Hilt

Android官方新推的DI庫 Hilt

Hilt是Google Android官方新推薦的依賴注入工具.
已加入到官方文檔: Dependency injection with Hilt. 目前是alpha release階段.

Hilt是在Dagger之上, Hilt單詞的意思是: 刀把, 柄.
代碼庫還是這個google/dagger.

Hilt的出現, 讓我想起了曾經曇花一現的dagger.android, 不知道hilt能不能經得住時間的考驗.

本文介紹Hilt的基本使用. 熟悉dagger的朋友可能會發現很容易.

Hilt是花里胡哨的小打小鬧? 還是下一個主流工具? 讓我們拭目以待.

Codelab練習例子

  • Codelab: Using Hilt in your Android app.

我的Fork: https://github.com/mengdd/android-hilt.

這個項目最開始是一個用ServiceLocator手動注入的例子, 功能是記錄用戶點擊button操作, 显示log. 有兩個Fragment和Activity.

通過Codelab中一系列步驟的改造, 最終改成用Hilt做依賴注入.

本文舉例就用其中的代碼片段了.

原repo還貼心地附上了改造前後的對比diff: Full codelab comparison.

Hilt依賴添加

project root: build.gradle:

buildscript {
    ext.hilt_version = '2.28-alpha'
    ...
    dependencies {
        ...
        classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
    }
}

需要Android 4.0以上.

app/build.gradle:

apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

android {
    ...
}

dependencies {
    // Hilt dependencies
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"

    // Hilt testing dependency
    androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
    // Make Hilt generate code in the androidTest folder
    kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
}

後面兩個是測試的依賴.

概念, 用詞解釋

  • Container, 對應Component.
  • Bindings, 對應依賴.
The information Hilt has about how to provide instances of different types are also called bindings.
  • Component hierarchy是指依賴在當前component中可以用, 也可以在它包含的child component中用. 舉例: application容器中的依賴activity可以用, 但是反過來不行.

Hilt基本使用

  • @HiltAndroidApp: 標記在Application類上, 觸發代碼生成, application container是整個app的parent container.
@HiltAndroidApp
class LogApplication : Application()
  • @AndroidEntryPoint: 標記在Activity和Fragment上. 創建了一個和當前Activity/fragment生命周期相關的container. 目前支持的類型是: Activity, Fragment, View, Service, BroadcastReceiver.
@AndroidEntryPoint
class ExampleActivity : AppCompatActivity() { ... }

每次Fragment(或Activity等)創建都會有它對應的container實例.

  • 字段注入: 用@Inject標記字段, 注意字段不能是private的.
@AndroidEntryPoint
class LogsFragment : Fragment() {

    @Inject
    lateinit var dateFormatter: DateFormatter
    ...
}


Component lifetimes可以看到每種類型的component創建和注入的時間.

Activity是onCreate(), Fragment是onAttach().

對Fragment來說, 在onAttach()的時候完成了對象的注入, 之後訪問對象都沒有問題.

  • 提供依賴: 用@Inject標記構造器.
class DateFormatter @Inject constructor() {
    ...
}

它的依賴可以在構造參數中標明.

Hilt的Scope支持

默認所有的依賴都是沒有scope的, 每次注入依賴都創建新的實例.
Hilt自動在對應的生命周期創建/銷毀對象: Component lifetimes.

也可以把依賴scope到某個component, 這樣在這個component內, 依賴就是單例.

  • scope: @Singleton: application container的scope, 說明是application範圍內的單例. @ActivityScoped對應activity component.

所有可用的scope: Component scopes.

module

module的使用基本和dagger一樣, 用來提供一些無法用構造@Inject的依賴, 比如接口, 第三方庫類型, Builder模式構造的對象等.

  • @Module: 標記這是一個module. 在Kotlin代碼中, module可以是一個object.
  • @Provides: 標記方法, 提供返回值類型的依賴.
  • @Binds: 標記抽象方法, 返回接口類型, 實現是方法的唯一參數.

Hilt多了一個註解:

  • @InstallIn: 指明module對應哪個container, 也即Component.
    Generated components for Android classes
@InstallIn(ApplicationComponent::class)
@Module
object DatabaseModule {

    @Provides
    @Singleton
    fun provideDatabase(@ApplicationContext appContext: Context): AppDatabase {
        return Room.databaseBuilder(
            appContext,
            AppDatabase::class.java,
            "logging.db"
        ).build()
    }

    @Provides
    fun provideLogDao(database: AppDatabase): LogDao {
        return database.logDao()
    }
}

module的拆分

module的名字最好能傳達它提供了什麼類型的依賴, 所以多種依賴拆分多個modules寫比較好.

@InstallIn(ActivityComponent::class)
@Module
abstract class NavigationModule {
    @Binds
    abstract fun bindNavigator(impl: AppNavigatorImpl): AppNavigator
}

@Binds@Provides不能放在同一個module里.
因為@Binds需要module是一個abstract class, 而@Provides需要module是一個object.
放一起會報錯: error: A @Module may not contain both non-static and abstract binding methods.

默認依賴

有一些默認依賴是已經有的, 比如:

  • @ApplicationContext.
  • @ActivityContext.

可以直接作為@Provides方法或@Inject構造的參數.

默認依賴是和component對應的.

Component default bindings

Qualifier

要提供同一個接口的不同實現, 可以用不同的註解來標記. (dagger之前用的是@Named).

A qualifier is an annotation used to identify a binding.

舉例: LoggerDataSource接口提供了內存和數據庫兩種實現.

定義兩個註解:

@Qualifier
annotation class InMemoryLogger

@Qualifier
annotation class DatabaseLogger

module中提供的時候用來標記相應的依賴:

@InstallIn(ApplicationComponent::class)
@Module
abstract class LoggingDatabaseModule {

    @DatabaseLogger
    @Singleton
    @Binds
    abstract fun bindDatabaseLogger(impl: LoggerLocalDataSource): LoggerDataSource
}

@InstallIn(ActivityComponent::class)
@Module
abstract class LoggingInMemoryModule {

    @InMemoryLogger
    @ActivityScoped
    @Binds
    abstract fun bindInMemoryLogger(impl: LoggerInMemoryDataSource): LoggerDataSource
}

這裏用了兩個module因為它們對應兩個不同的component, 一個是application一個是activity, 依賴也是相應的scope.

注入的時候也對應加上:

@InMemoryLogger
@Inject
lateinit var logger: LoggerDataSource

@EntryPoint

Hilt支持最常用的Android組件, 對於默認不支持的類型, 如果還想做字段注入, 需要用@EntryPoint.

注意這裏只是限制了字段注入的情況, 自定義類型一般用構造注入比較方便(如果能用的話).

@EntryPoint的意思就是一個邊界點, 這裏可以通往Hilt的世界, 得到容器提供的依賴對象們.

Codelab中的例子是一個ContentProvider.

關鍵的部分是這段代碼:

@InstallIn(ApplicationComponent::class)
@EntryPoint
interface LogsContentProviderEntryPoint {
    fun logDao(): LogDao
}

private fun getLogDao(appContext: Context): LogDao {
    val hiltEntryPoint = EntryPointAccessors.fromApplication(
        appContext,
        LogsContentProviderEntryPoint::class.java
    )
    return hiltEntryPoint.logDao()
}

Hilt and Dagger

當初的dagger.android已被放棄, 它是為了簡化dagger在Android上的使用而單獨推出的. (根據Activity和Fragment的生命周期, 開發者不用手動調用inject方法, 但是確實最開始的setup code比較多.)

Hilt相對於Dagger來說, 簡化了幾個點:

  • 不用自己創建Component.
  • 不用手動調用inject()方法來完成字段注入.
  • 不用自己在Application中保存component.
  • 提供了一些Scope, 不用自己定義和寫.
  • 提供了一些默認依賴, 比如Context.

總體來說Hilt就是針對Android做的定製, 讓依賴注入框架用起來更方便. 畢竟dagger是一個java注入庫, 它的應用範圍不限於Android.

因為Hilt和Dagger可以共存, 可以逐步遷移. 既然官方推薦了, 可以在項目內小範圍地先試試.

最後推薦這個cheat sheet

Reference

  • Dependency Injection on Android with Hilt
  • Dependency injection with Hilt
  • Dagger Hilt

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

網頁設計公司推薦不同的風格,搶佔消費者視覺第一線

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

※自行創業缺乏曝光? 網頁設計幫您第一時間規劃公司的形象門面

南投搬家公司費用需注意的眉眉角角,別等搬了再說!

※教你寫出一流的銷售文案?