-
ViewModel 은 activity 나 fragment 에서 사용되는 data 를 준비하고 관리하는 역할을 하는 클래스이다.
이 녀석은 activity 와 fragment 를 비롯한 앱 전반과의 통신을 관리한다.
-
ViewModel 은 항상 fragment 나 activity 와 같은 scope 안에서 생성된다.
그리고 scope 이 살아있는 동안 계속 유지된다.
이 말은 Configutation change 로 인해 destory 되더라도, ViewModel 은 destroy 되지 않는다.
새로운 owner instance (재생성된 Activity)는 존재하는(기존 Activity 에 의해 생성된) ViewModel 에 재연결된다.

-
ViewModel 의 목적은 Activity 나 Fragment 에서 사용되는 정보를 얻고 유지하는 것이다.
Activity, Fragment 는 ViewModel 의 변화를 observe 할 수 있다.
ViewModel 은 보통 LiveData 나 Data binding 을 통해서 그 정보를 노출한다.
또는 좋아하는 framework 의 observable 기능을 사용하면 된다. (ex. Rx)
-
ViewModel 의 유일한 역할은 UI 를 위해 data 를 관리하는 것이다.
ViewModel 이 절대 view hierarchy 에 접근하게 해서는 안 되고, Activity 나 Fragment 를 참조하고 있으면 안 된다.
-
다음이 Activity 에서 사용하는 전형적인 패턴이다.
// AppCompatActivity 를 상속 & Kotlin 을 사용하는 경우에는 ViewModelProvider 를 사용하지 않고, viewModels() 함수를 통해 assign 할 수 있다.
public class UserActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_layout);
// Kotlin style : private val viewModel: UserModel by viewModels()
// Fragment 에서 Activity ViewModel 을 share 하는 경우에는 by activityViewModels()
final UserModel viewModel = new ViewModelProvider(this).get(UserModel.class);
viewModel.userLiveData.observer(this, new Observer() {
@Override
public void onChanged(@Nullable User data) {
// update .
}
});
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewModel.doAction();
}
});
}
}public class UserModel extends ViewModel {
private final MutableLiveData<User> userLiveData = new MutableLiveData<>();
public LiveData<User> getUser() {
return userLiveData;
}
public UserModel() {
// trigger user load.
}
void doAction() {
// depending on the action, do necessary business logic calls and update the
// userLiveData.
}
}-
ViewModel 은 한 activity 의 fragment 간의 communication layer 로도 작동할 수 있다.
각각의 fragment 는 VIewModel 을 동일한 Activity 를 key 로 하여 얻을 수 있다.
이를 통해 fragment 간 통신 없는 decoupling 을 이룰 수 있다.
public class MyFragment extends Fragment {
public void onStart() {
UserModel userModel = new ViewModelProvider(requireActivity()).get(UserModel.class);
}
}-
protected 함수
onCleared() : ViewModel 이 더 이상 사용되지 않아 곧 destroy 될 때 불린다.
-
참고 자료 : https://developer.android.com/reference/androidx/lifecycle/ViewModel.html
끝
'프로그래밍 놀이터 > 안드로이드, Java' 카테고리의 다른 글
| [android] context 마스터 하기! (0) | 2021.01.26 |
|---|---|
| [android] ViewModel & LiveData 의 pattern & anti-pattern (0) | 2021.01.22 |
| [android] LiveData 에 대해 알아볼까 (0) | 2021.01.20 |
| #5 모바일 앱 보안 강화 - 안드로이드 모바일 앱 모의해킹 (0) | 2020.11.23 |
| #4 앱 자동 분석 시스템 - 안드로이드 모바일 앱 모의해킹 (0) | 2020.11.22 |
댓글