Home > front end >  How to create viewmodel instance for a lot of fragments?
How to create viewmodel instance for a lot of fragments?

Time:06-27

I have a lot of fragments in my activity, each of which uses own methods in the VM. In each of fragment I have to create viewmodel instance before using it in such way:

val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
    this@FragmentName,
    AppVMFactory(mainRepository)
).get(AppViewModel::class.java)

in my MainRepository I have my requests methods:

class MainRepository constructor(private val retrofitService: RetrofitService) {
    suspend fun someMethod() = retrofitService.someMethod()
}

and in retrofit service I have api requests methods. The main question is how I cane create viewModel instance only one time without using this code:

val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
    this@FragmentName,
    AppVMFactory(mainRepository)
).get(AppViewModel::class.java)

in each fragment. At the beginning I thought about single fragment parent, but I'm not sure whether it will be ok for dialogFragment and also how it will be able to use with data binding. Maybe I can use some features of android development about which I don't know?

CodePudding user response:

You can use sharedViewModel and it will be shared across all fragments in activity https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

  • Related