【问题标题】:Where is the defaultDispatche instanced by Hilt?Hilt 的默认 Dispatcher 实例在哪里?
【发布时间】:2021-12-30 06:13:15
【问题描述】:

代码A来自官方样本project的末尾分支。

项目使用Hilt实现依赖注入。

我搜索了整个项目,我只找到了代码annotation class DefaultDispatcher,但我无法理解代码的含义。

Hilt 实例化的 defaultDispatche 在哪里?

代码 A

@HiltViewModel
class MainViewModel @Inject constructor(
    private val destinationsRepository: DestinationsRepository,
    @DefaultDispatcher private val defaultDispatcher: CoroutineDispatcher
) : ViewModel() {
   ...
}



@OptIn(ExperimentalMaterialApi::class)
@Composable
fun CraneHomeContent(
    onExploreItemClicked: OnExploreItemClicked,
    openDrawer: () -> Unit,
    modifier: Modifier = Modifier,
    viewModel: MainViewModel = viewModel(),
) {
   ...
}


@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class DefaultDispatcher

【问题讨论】:

    标签: kotlin dagger-hilt


    【解决方案1】:

    你应该有一个像这样声明的模块

    @Module
    object DispatcherModule {
        @DefaultDispatcher
        @Provides
        fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
       
    }
    

    现在您创建这个类以便使用@DefaultDispatcher 作为注解

    @Retention(AnnotationRetention.BINARY)
    @Qualifier
    annotation class DefaultDispatcher
    

    更多详情,请访问here

    在您的示例项目的here 中,您共享的内容完全是这样写的。

    这意味着@DefaultDispatcher 将用作注释,其中值将由DispatcherModule 提供

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2020-04-02
      相关资源
      最近更新 更多