- I have a common fragment which is used by 3 different navgraph. this fragment has 3 different navGraphViewModels but using only one of them whereever it is called from using their fragment id's It is not a good design . I need to make this fragment more generic
- I am implementing these 3 navGraphViewModels and 2 of them are unnecessery.(becouse you cannot declare withaout instantiating those navGraphViewModels.) Please any good architect or a program designer can find a solution for me .
@AndroidEntryPoint
class CommonFragment: BaseFragment<CommonFragmentBinding>() {
//todo should be implemented more generic
private val bookSharedViewModel: BookSharedViewModel by navGraphViewModels(R.id.book)
private val tripSharedViewModel: TripsSharedViewModel by navGraphViewModels(R.id.trips)
private val homeSharedViewModel: HomeSharedViewModel by navGraphViewModels(R.id.home)
private val viewModel: CommonFragmentViewModel by viewModels()
private var label: String? = null
override fun inflateBinding(
inflater: LayoutInflater,
container: ViewGroup?
): CommonFragmentBinding =
CommonFragmentBinding.inflate(
inflater,
container,
false
)
@SuppressLint("RestrictedApi")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
label = findNavController().previousBackStackEntry?.destination?.displayName
viewModel.editTripModel = getFromSharedModel()
}
private fun getFromSharedModel() = when (label) {
"${BuildConfig.APPLICATION_ID}:id/bookFragment" -> bookSharedViewModel.editTripModel
"${BuildConfig.APPLICATION_ID}:id/tripEditFragment" -> tripSharedViewModel.editTripModel
"${BuildConfig.APPLICATION_ID}:id/homeEditFragment" -> homeSharedViewModel.editTripModel
else -> null
}
Aucun commentaire:
Enregistrer un commentaire