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.

2 answers

  • answered 2020-02-16 11:16 Roshan Kumar

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

  • answered 2020-02-16 11:26 mahdi shahbazi

    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.