Is there a way to skip init method in viewmodel?

Viewed 28

Is there a way to not execute the init method when calling the viewmodel into the fragment?

This is how my fragment looks:

@AndroidEntryPoint
class WelcomeFragment : BaseFragment(R.layout.fragment_welcome) {

    //Here I call the viewmodel
    private val notificationViewModel: NotificationViewModel by viewModels()


This is the viewmodel:

@HiltViewModel
class NotificationViewModel @Inject constructor(
    screenAnalytics: SegmentScreenAnalytics,
) : BaseViewModel() {

    //I want to skip this method
    init {
        screenAnalytics.screenNotifications()
    }

EDIT: Sorry I didn't give the whole context before.

I call that viewmodel from another fragment too, and that fragment does need the code inside init to execute when the fragment is launched. What I would like excatly is to execute the init only when one of those fragments calls the viewmodel

Thanks a lot

2 Answers

You could try to send a bool parameter via SavedStateHandle to the viewmodel, then, inside the ini, check the bool state and execute screenAnalytics.screenNotifications() based on that.

Related