[英]Android Hilt injecting interface to a viewmodel impelemented by an activity
New to DI, Using Hilt I'm trying to inject an interface implemented by an activty to a viewmodel like this: DI 新手,使用 Hilt 我正在尝试将 activty 实现的接口注入到这样的视图模型中:
Activity class:活动 class:
@AndroidEntryPoint
class MainActivity : AppCompatActivity(), AnInterface{
private val mainViewModel : MainViewModel by viewModels()
// .....
}
ViewModel:视图模型:
@HiltViewModel
class MainViewModel : ViewModel() @Inject constructor(anInterface : AnInterface){
}
Module:模块:
@Module
@InstallIn(ActivityComponent::class)
class ActivityModule {
@Provides
fun provideAnInterface(activity: Activity) : AnInterface = activty as AnInterface
}
Gives me error:给我错误:
AnInterface cannot be provided without an @Provides-annotated method.
You should not pass Activity's reference to ViewModel
That clearly violates the loose coupling feature of MVVM.不应将 Activity 的引用传递给
ViewModel
,这显然违反了 MVVM 的松耦合特性。 Dependency flows inwards in MVVM.依赖在 MVVM 中向内流动。 Use
LiveData
instead to observe the Data from ViewModel
in Activity/Fragment do not use an Interface.改用
LiveData
来观察 Activity/Fragment 中ViewModel
的数据,不要使用接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.