如何从Android应用程序注入变量

eeq64g8w  于 2023-04-18  发布在  Android
关注(0)|答案(1)|浏览(122)

我在Application中定义了一个变量,我需要将它注入WorkViewModal

@HiltAndroidApp
class SageApplication : Application() {
  val applicationScope = CoroutineScope(SupervisorJob())
}

但是我不能这样做,因为ApplicationContext没有我的自定义属性applicationScope

@HiltViewModel
class WorkViewModel @Inject constructor(
  @ApplicationContext private val applicationContext: ApplicationContext
) : ViewModel() {

我也不能使用@Provides来提供SageApplication的示例,它还需要提供SageApplication,但我不确定这样做是否正确。

@InstallIn(SingletonComponent::class)
@Module
class ApplicationModule {
  @Provides
  fun provideApplicationScope(@ApplicationContext application: SageApplication) = application.applicationScope
}

我想像这样将applicationScope注入到ViewModel中:

@HiltViewModel
class WorkViewModel @Inject constructor(
  private val applicationScope: CoroutineScope
) : ViewModel()

我该怎么办?

ni65a41a

ni65a41a1#

您可以定义一个自定义Hilt模块,该模块提供您的SageApplication示例并将applicationScope公开为单例依赖项。下面是一个示例:

@InstallIn(SingletonComponent::class)
@Module
class ApplicationModule {
  
  @Singleton
  @Provides
  fun provideSageApplication(@ApplicationContext appContext: Context): SageApplication {
    return appContext as SageApplication
  }

  @Singleton
  @Provides
  fun provideApplicationScope(application: SageApplication): CoroutineScope {
    return application.applicationScope
  }
}

@HiltViewModel
class WorkViewModel @Inject constructor(
  private val applicationScope: CoroutineScope
) : ViewModel() {
  // ...
}

确保将ApplicationModule添加到SageApplication类中的@HiltAndroidApp注解中:

kotlin
Copy code
@HiltAndroidApp
class SageApplication : Application() {
  val applicationScope = CoroutineScope(SupervisorJob())
}

通过这种设置,Hilt将向WorkViewModel提供包含applicationScope的SageApplication示例。

相关问题