Mahmoud Ibrahim
Mahmoud Ibrahim

Reputation: 1085

Why my ViewModel is still alive after I replaced current fragment in Android?

Example, If I replaced 'fragmentA' with 'fragmentB', the 'viewModelA' of fragmentA is still live. why ?

onCreate() of Fragment

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    viewModel = ViewModelProvider.NewInstanceFactory().create(InvoicesViewModel::class.java)
}

ViewModel

class InvoicesViewModel : ViewModel() {

init {
    getInvoices()
}

private fun getInvoices() {

    viewModelScope.launch {

        val response = safeApiCall() {
            // Call API here
        }

        while (true) {
            delay(1000)
            println("Still printing although the fragment of this viewModel destroied")
        }

        if (response is ResultWrapper.Success) {
            // Do work here
        }
    }
}
}

This method used to replace fragment

fun replaceFragment(activity: Context, fragment: Fragment, TAG: String) {
    val myContext = activity as AppCompatActivity
    val transaction = myContext.supportFragmentManager.beginTransaction()
    transaction.replace(R.id.content_frame, fragment, TAG)
    transaction.commitNow()
}

You will note the while loop inside the Coroutine still work although after replace fragment to another fragment.

Upvotes: 0

Views: 832

Answers (2)

mahdi shahbazi
mahdi shahbazi

Reputation: 2132

this is about your implementation of ViewModelProvider. use this way for creating your viewModel.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewModel = ViewModelProvider(this).get(InvoicesViewModel::class.java)
}

in this way you give your fragment as live scope of view model.

Upvotes: 1

Roshan Kumar
Roshan Kumar

Reputation: 66

Check, if you have created the ViewModel in Activity passing the context of activity or fragment.

Upvotes: 0

Related Questions