我使用Dagger-Hilt作为依赖项注入,并且我不知道如何在抽象类中进行字段注入。
// @ViewModelScoped
abstract class BaseUseCase<Params, Return>{
// lateinit var not initiazlied. Cannot be injected
@Inject
lateinit var errorHandler: ErrorHandler
fun execute(@nullable params: Params?=null): Flow<DataState<Return>> = flow {
emit(Datastate.Loading)
emit(executeRealization(params))
...
}.catch{ e->
when(e){
...
is Exception -> {
...
errorHandler.handleError(e.message ?: "Unknown Error")
}
}
}
protected abstract fun executeRealization(@Nullable params: Params?=null): DataState<Return>
}第二包
作为单例使用匕首柄的(AppModule.kt)
问题
发布于 2021-10-25 09:25:30
如何在抽象类中进行字段注入?
目前不支持这一点。
您可以考虑在这两种方法中重构代码。
优先逼近
将异常/错误处理向上移动到UI,这将包括ViewModel的方法。
这样,您就可以构造函数注入错误处理程序,然后执行UseCase并将处理程序封装在它周围。
让我们看看一个可能的解决方案,在草图中,我们将使用干净的架构方法;
ViewModel.kt
@HiltViewModel
class YourViewModel @Inject constructor(private val errorHandler: ErrorHandler, private val useCase : SpecificUseCase) : ViewModel(){
suspend fun realizationFunction(params : Params?=null) : Flow<DataState<Return>> = flow {
emit(Datastate.Loading)
try{
emit(useCase(params))
}catch(exception : Exception){
errorHandler.handleError(e.message ?: "Unknown Error")
}
}
}在您的特定useCase上,我建议您使用存储库模式来执行您的函数,以便分离关注点,而不是在用例中执行您的函数。
第二次逼近
这种方法包括将错误处理程序深入到链中,并在存储库实现中注入错误处理程序。
这将使您有机会在try/catch中运行特定的函数/服务调用,并在其中处理错误。
第二种方法的缺点可能包括返回错误结果的挑战,但是合并一个资源类将使其无缝--似乎您已经有了一个,DataState。
class YourRepositoryImpl(private val errorHandler: ErrorHandler) : YourRepositoryInterface {
override suspend fun doSomething(params : Params?) : Flow<DataState<Return>> {
//call your function and use the error handler
}
}这为您提供了更干净的代码和更好的错误处理。
还是我漏掉了什么?
您可能对阅读很多关于应用程序架构和分离关注点的文章感兴趣。
https://stackoverflow.com/questions/69702157
复制相似问题