[英]Provide domain-layer UseCase classes with HILT
我正在从Google I/O 的应用程序到我自己的应用程序实现一些架构设计,但我在他们的应用程序中遇到了一些让我感到困惑的东西。
他们有一个带有存储库用例的域层,我通常在我的应用程序中使用它。 但是,我必须在我的应用程序中为这些用例提供匕首。 但在 Google 的 I/O 应用程序上,我找不到任何提供这些用例的模块。 当与注释 @HiltViewModel 的视图模型(在我自己的应用程序中)一起使用时,它似乎有效? 不知何故,这些被注入到我的视图模型中。 我必须通过 Hilt 提供所有用例的依赖项(存储库等),但我不必通过 Hilt 提供任何用例。
这是它在我的代码中的外观示例。
用例:
abstract class UseCase<in P, R>(private val coroutineDispatcher: CoroutineDispatcher) {
suspend operator fun invoke(parameters: P): Resource<R> {
return try {
withContext(coroutineDispatcher) {
execute(parameters).let {
Resource.Success(it)
}
}
} catch (e: Exception) {
Timber.d(e)
Resource.Error(e.toString())
}
}
@Throws(RuntimeException::class)
protected abstract suspend fun execute(parameters: P): R
}
用例的具体实现:
class GetListUseCase @Inject constructor(
private val coroutineDispatcher: CoroutineDispatcher,
private val remoteRepository: RemoteRepository
): UseCase<ListRequest,ItemsList>(coroutineDispatcher) {
override suspend fun execute(parameters: ListRequest): ItemsList{
return remoteRepository.getList(parameters)
}
}
视图模型:
@HiltViewModel
class DetailViewModel @Inject constructor(
private val GetListUseCase: getListUseCase
): ViewModel() {
suspend fun getList(): Resource<ItemsList> {
getPokemonListUseCase.invoke(ListRequest(3))
}
}
提供的回购示例:
@Singleton
@Provides
fun provideRemoteRepository(
api: Api
): RemoteRepository = RemoteRepositoryImpl(api)
远程回购:
@ActivityScoped
class RemoteRepositoryImpl @Inject constructor(
private val api: Api
): RemoteRepository {
override suspend fun getList(request: ListRequest): PokemonList {
return api.getPokemonList(request.limit, request.offset)
}
}
我的问题是:这是怎么回事? 为什么我不必通过 Hilt 提供用例? 还是我的设计有误,即使可行,我也应该通过 Hilt 提供用例?
编辑:
你的设计很棒! 这并没有错,但是是的,如果您将用例放在一个单独的模块中并根据您的需要确定它们的范围,您可以为您的用例添加一些额外的上下文。 模块主要存在于当你确实有第三方依赖项(最简单的例子是 OkHTTPClient)或者当你有 interface -> impl of the interface,或者你想明显地限制/延长组件的生命周期/可见性的情况下。
目前,您正在告诉 Hilt 如何通过使用 @Inject 注释其构造函数来提供 GetListUseCase 的实例,并且 Hilt 已经知道什么是“CoroutineDispatcher”(因为它是由协程模块中的 @Provides 提供的,对吗?)以及 RemoteRepository 是什么(因为您正在注入接口,但在幕后,您在@Provides 的 repo 模块中提供了它的真正实现)。
所以这就像说 - 给我一个具有两个构造函数依赖项的用例类的实例,并且它们都是 Hilt 已知的,所以它不会令人困惑。
如果你想拥有一个范围绑定/组件(如这里解释的)或将你的用例标记为单例,那么你必须创建一个 UseCaseModule 并在那里确定你的用例组件的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.