I would like to show the one service result to the UI and the result has been modified dynamically. So, I have created MutableLiveData.
ResultViewModel
class ResultViewModel @Inject constructor(
private val lane: ResultManager
) : ViewModel() {
val result= MutableLiveData<String>()
init {
result.listener = object : ResultListener {
override fun OnChange(value: String?) {
result.postValue(value)
}
}
}
}
and created the Generic viewmodel factory
class ViewModelFactory @Inject constructor(
private val creators: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator: Provider<out ViewModel>? = creators[modelClass]
if (creator == null) {
for ((key, value) in creators) {
if (modelClass.isAssignableFrom(key)) {
creator = value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("Unknown model class: $modelClass")
}
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
and viewmodel for this factory has been created and added to the app component
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@MapKey
internal annotation class ViewModelKey(val value: KClass<out ViewModel>)
@Module
abstract class ViewModelModule {
@Binds
abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
@Binds
@IntoMap
@ViewModelKey(ResultViewModel::class)
abstract fun refultViewModel(viewModel: ResultViewModel ): ViewModel
}
and in my app component
@Singleton
@Component
(modules = [AppModule::class,
ViewModelModule::class])
interface AppComponent {
fun Inject(result: ResultModule): ResultComponent
}
@Subcomponent(modules = [ResultModule::class, ResultViewModelModule::class])
interface ResultComponent {
fun inject(activity: MainActivity)
}
and i have resultmodule as follows,
@Module
class ResultModule(private val resultId: Int) {
@Singleton
@Provides
fun refultManager(manager: ResultMonitor): ResultManager = manager.getManager(0)
}
In my main activity, I tried to get the app component and injected that activity
@Inject lateinit var viewModelFactory: ViewModelFactory
private val resultViewModel : ResultViewModel by viewModels { viewModelFactory }
in onCreate, I tried to inject the activity.
var appComponent = Resultapp.Getcomponent()
appComponent.Inject(AfccLaneModule(0)).Inject(this)
but facing, Caused by: kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialize
unable to find the route cause of the issue.