avatar🐀
霂枯木霂枯木的小站

To witness the sunrise and the sea of blossoms.

行可兼知,而知不可兼行

Hilt依赖注入

1. 插件 ​

    id("com.google.devtools.ksp") version "2.3.10" apply false
    id("com.google.dagger.hilt.android") version "2.60.1" apply false
    id("com.google.devtools.ksp")
    id("com.google.dagger.hilt.android")

2. 依赖 ​

    implementation("com.google.dagger:hilt-android:2.60.1")
    implementation("androidx.hilt:hilt-navigation-compose:1.2.0")
    ksp("com.google.dagger:hilt-android-compiler:2.60.1")

3. Application类 ​

@HiltAndroidApp
class MyApp : Application()

AndroidManifest.xml

<application android:name=".MyApp"/>

Activity

@AndroidEntryPoint
class MainActivity : ComponentActivity()

4. viewModel使用 ​

@HiltViewModel
class MyViewModel @Inject constructor() : ViewModel()

用法a,必须在@AndroidEntryPoint中使用

val myViewModel by viewModels<MyViewModel>()

用法b

val myViewModel = hiltModels<MyViewModel>()

5. 自定义Module使用 ​

@Module
@InstallIn(SingletonComponent::class)//SingletonComponent表示单例
object NetworkModule {

    @Provides
    @Singleton//单例
    fun provideOkHttp(): OkHttpClient =
        OkHttpClient.Builder().build()

    @Provides
    @Singleton
    fun provideRetrofit(client: OkHttpClient): Retrofit =
        Retrofit.Builder()
            .baseUrl("https://api.example.com/")
            .client(client)
            .addConverterFactory(MoshiConverterFactory.create())
            .build()

    @Provides
    @Singleton
    fun provideApiService(retrofit: Retrofit): ApiService =
        retrofit.create(ApiService::class.java)
}

@Inject构造注入

class UserRepository @Inject constructor(
    private val api: ApiService,
    private val dao: UserDao
)

@AndroidEntryPoint注入

    @Inject
    lateinit var userRepository: UserRepository

6. 其他 ​

构造注入context

@ApplicationContext context: Context

@Binds和@Provides功能类似,如果抽象类已经通过@Inject注入了,那么使用@Binds更简洁

@Module
@InstallIn(SingletonComponent::class)
abstract class DataModel {
    @Binds
    @Singleton
    abstract fun bindRepository(
        repository: RepositoryImpl
    ): Repository
}
API Level对照表
Room框架的基本使用
由 Valaxy v1.2.0 驱动|主题-Yunv1.2.0