-
과연 Activity/Fragment가 Finished되면 View Model은 어떻게 될까?프로그래밍/Android 2017. 8. 29. 22:50반응형
ViewModel은 MVVM 패턴에서 VM의 역할로 사용자의 눈에 보이는 데이터를 저장하고 관리하며 Activity/Fragment의 생명주기동안 데이터를 들고 있다.
그렇다면 과연 Activity/Fragment가 Finished되면 View Model은 어떻게 될까?
ViewModel 라이프 사이클은 다음과 같다. Activity에 바인드 되어서 onDestroy시 같이 소멸되는 것이 원칙이다. rotation과 같이 ViewModel 객체가 다시 만들어져야할 경우는 비효율적인 경우이므로 ViewModel 객체가 재생성되지 않는다.
Another problem is that, these UI controllers (activities, fragments, and so on) frequently need to make some asynchronous calls which may take some time to return. The UI controller needs to manage these calls and clean them up when it is destroyed to avoid potential memory leaks. This requires a lot of maintenance, and in the case where the object is re-created for a configuration change, it is a waste of resources since it needs to re-issue the same call.
If the activity is re-created, it receives the same MyViewModel instance that was created by the previous activity. When the owner activity is finished, the Framework calls ViewModel’s onCleared() method so that it can clean up resources.
ViewModel instances are stored in a global static Map and reattached automatically to corresponding Activity/Fragment. When there is no need for the ViewModel anymore (Activity finished) the instance is destroyed.
하지만 Activity 생명주기는 시스템에 의해 좌우되므로 ViewModel이 View나 Activity Context를 들고 있게 하는 것은 위험하다. 생명주기가 필요하다면
AndroidViewModel class를 상속받으면 된다.
Note: Since the ViewModel outlives specific activity and fragment instantiations, it should never reference a View, or any class that may hold a reference to the activity context. If the ViewModel needs the Application context (for example, to find a system service), it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor (since Application class extends Context).
https://github.com/jakubkinst/Android-ViewModelBinding
example - http://www.tivix.com/blog/android-data-binding-mvvm/
반응형'프로그래밍 > Android' 카테고리의 다른 글
Property View (0) 2017.12.20 Introduction to Physics-based animations in Android (0) 2017.09.06 지니모션 Googleplay 설치 (0) 2017.07.31 What's new in Support Library (0) 2017.06.07 Android O, Background Check and other insights into the evolution of the Android Operating System Framework (0) 2017.06.07