Answer the question
In order to leave comments, you need to log in
How to access the functions of the ViewModel in the Activity, which is implemented in the Fragment?
How can you access the someFunction() function in this ViewModel in an Activity if this ViewModel is used in a Fragment?
ExampleViewModel.kt code:
class ExampleViewModel(private val repo: ApiRepository) : ViewModel() {
private val mutableLiveData = MutableLiveData<Resource<List<Item>>>()
lateinit var item: UserItem
fun getLiveData(): LiveData<Resource<List<Item>>> {
return mutableLiveData
}
fun someFunction() {
//...
}
//...
}
class ExampleFragment : Fragment() {
private val exampleViewModel: ExampleViewModel by viewModels { ViewModelsProviderFactory }
override fun onCreateView(
//...
setObservers()
}
private fun setObservers() {
exampleViewModel.getLiveData().observe(viewLifecycleOwner, {
//..
}
class MainActivity : AppCompatActivity() {
private var exampleFragment: Fragment = ExampleFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//..
// ?? использовать например тут: someFunction() из ExampleViewModel , либо в другом фрагменте
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question