我在我的片段中使用以下代码创建了视图模型:
areaViewModel = ViewModelProvider(
this, AreaViewModelFactory(AreaController.repository, currentPanelId, areaId)
)[AreaViewModel::class.java]
ViewModel和ViewModelFactory的实现:
class AreaViewModelFactory (private val repository: AreaRepository): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(AreaViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return AreaViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
class AreaViewModel@Inject constructor(private val repository: AreaRepository) : ViewModel(){
companion object {
const val TAG: String = "AreaViewModel"
}
init {
Log.i("AreaViewModel", "AreaViewModel created!")
}
private val _areaState = MutableStateFlow<Resource<Area>>(Resource.loading(null))
val areaState: StateFlow<Resource<Area>>
get() = _areaState
fun getAreaById(panelId: Int, areaId: Int){
_areaState.value = Resource.loading(null)
viewModelScope.launch {
repository.getAreaById(panelId, areaId) .catch { e ->
_areaState.value = Resource.error(e.toString(), null)
}
.collect { it ->
_areaState.value = Resource.success(it)
}
}
}
override fun onCleared() {
Log.i("AreaViewModel", "AreaViewModel destroyed!")
super.onCleared()
}
}
然后通过片段管理器删除片段:
private void removeControlFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
List<Fragment> fragmentList = fragmentManager.getFragments();
for(int i = 0; i < fragmentList.size(); i++) {
if (fragmentList.get(i) instanceof ControlFragment) {
fragmentManager.beginTransaction().remove(fragmentList.get(i)).commit();
}
}
}
我期望在ViewModel的对应片段被销毁时调用它的onCleared。然而这并没有发生。
请指出遗漏或错误的地方?
1条答案
按热度按时间k5ifujac1#
你应该检查viewmodel的生命周期,如文档所述。
视图模型生命周期