Architecture-components-samples: ViewModel's onCleared is not be call after fragment is destroyed.

Created on 12 Apr 2018  路  8Comments  路  Source: android/architecture-components-samples

I have a very simple ViewModel.

class TestViewModel: ViewModel() {
    override fun onCleared() {
        super.onCleared()
        Log.d("TEST", "clear")
    }
}

and I use it in a fragment

class TestFragment() {
    //....
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        vm = ViewModelProviders.of(this).get(TestViewModel::class.java)
    }
}

and the onCleared method is not be called after activity finished.

If I want the method to be called, I have to remove fragment manually before finish activity.

I am not sure it is feature or bug.

Most helpful comment

What's about same bug in androidX?
androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha05

Update: seems like my case slightly different, i will open issue in issuetracker.

All 8 comments

This is a known bug, already fixed in 27.1.1.
https://developer.android.com/topic/libraries/support-library/revisions.html

Please report bugs in the library in the correct tracker. This is just for samples.

@JoseAlcerreca Thank you

@JoseAlcerreca Was it fixed on 27.1.1 ? Or found? Is there a workaround?
Someone claimed it was fixed only on 28.0.0 : https://stackoverflow.com/a/49411448/878126

What's about same bug in androidX?
androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha05

Update: seems like my case slightly different, i will open issue in issuetracker.

Same bug in androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha05

Exists in v2.1.0 (stable) too

For a stable onCleared call, the following version works well:
def view_model = "2.3.0-alpha03"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$view_model"

I apologize, but even this version is not stable.

@Vlad-Shesternin There is already a newer version:

androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0-beta01

Was this page helpful?
0 / 5 - 0 ratings