简体   繁体   中英

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:

Activity 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. Dependency flows inwards in MVVM. Use LiveData instead to observe the Data from ViewModel in Activity/Fragment do not use an Interface.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM