티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

AndroidViewModel vs ViewModel
AndroidViewModel과 ViewModel의 차이점
문제 내용
With the introduction of the Android Architecture Components library, several new classes were introduced, including AndroidViewModel
and ViewModel
. However, I'm having trouble figuring out the difference between these two classes. The documentation succinctly describes AndroidViewModel
as follows:
Android Architecture Components 라이브러리 도입으로 AndroidViewModel 및 ViewModel을 포함한 여러 새로운 클래스가 소개되었습니다. 그러나 저는 이 두 클래스의 차이점을 이해하는 데 어려움을 겪고 있습니다. 문서는 AndroidViewModel을 간결하게 다음과 같이 설명합니다:
Application context aware
ViewModel
애플리케이션 컨텍스트를 인식하는 ViewModel
I appreciate the brevity, but what exactly does this imply? When should we choose to use AndroidViewModel
over ViewModel
and vice-versa?
간결함에 감사하지만 이것이 정확히 무엇을 의미합니까? ViewModel 대신 AndroidViewModel을 사용하거나 그 반대의 경우를 선택해야 하는 경우는 언제입니까?
높은 점수를 받은 Solution
AndroidViewModel provides Application context
AndroidViewModel은 Application context를 제공합니다.
If you need to use context inside your Viewmodel you should use AndroidViewModel (AVM), because it contains the application context. To retrieve the context call getApplication()
, otherwise use the regular ViewModel (VM).
만약 Viewmodel 내부에서 컨텍스트를 사용해야 한다면 AndroidViewModel (AVM)을 사용해야합니다. 왜냐하면 애플리케이션 컨텍스트를 포함하고 있기 때문입니다. 컨텍스트를 가져오려면 getApplication()을 호출하고, 그렇지 않은 경우에는 일반 ViewModel (VM)을 사용하세요.
AndroidViewModel has application context. We all know having static context instance is evil as it can cause memory leaks!! However, having static Application instance is not as bad as you might think because there is only one Application instance in the running application.
AndroidViewModel은 애플리케이션 컨텍스트를 가지고 있습니다. 우리는 모두 정적 컨텍스트 인스턴스를 가지고 있는 것이 메모리 누수를 발생시킬 수 있기 때문에 나쁜 것이라는 것을 알고 있습니다! 그러나 실행 중인 애플리케이션에서는 단 하나의 애플리케이션 인스턴스만 존재하기 때문에 정적 애플리케이션 인스턴스를 가지고 있는 것은 생각보다 나쁘지 않습니다.
Therefore, using and having Application instance in a specific class is not a problem in general. But, if an Application instance references them, it is a problem because of the reference cycle problem.
그러므로 특정 클래스에서 Application 인스턴스를 사용하거나 가지는 것은 일반적으로 문제가 되지 않습니다. 하지만 Application 인스턴스가 그들을 참조한다면, 참조 사이클 문제 때문에 문제가 됩니다.
See Also about Application Instance
Application Instance에 대한 추가 정보
AndroidViewModel Problematic for unit tests
AndroidViewModel은 유닛 테스트에 문제가 있습니다.
AVM provides application context which is problematic for unit testing. Unit tests should not deal with any of the Android lifecycle, such as context.
AVM은 애플리케이션 컨텍스트를 제공하기 때문에 유닛 테스트에 문제가 될 수 있습니다. 유닛 테스트는 컨텍스트와 같은 안드로이드 라이프사이클과 관련된 요소를 다루면 안 됩니다.
가장 최근 달린 Solution
AndroidViewModel is subclass of ViewModel. The Difference between them is we can pass Application Context which can be used whenever Application Context is required for example to instantiate Database in Repository.
AndroidViewModel은 ViewModel의 하위 클래스입니다. 둘의 차이점은 AndroidViewModel에서 애플리케이션 컨텍스트를 전달할 수 있으며, 이는 예를 들어 Repository에서 데이터베이스를 인스턴스화해야 하는 경우에 필요합니다.
AndroidViewModel is a Application context aware ViewModel.
AndroidViewModel은 애플리케이션 컨텍스트를 인식하는 ViewModel입니다.
AndroidViewModel:
public class PriceViewModel extends AndroidViewModel {
private PriceRepository priceRepository;
public PriceViewModel(@NonNull Application application) {
super(application);
priceRepository= new PriceRepository(application);
allPrices = priceRepository.getAllPrices();
}
ViewModel:
public class PriceViewModel extends ViewModel {
public PriceViewModel() {
super();
}
You Should use AndroidViewModel only when you require Application Context.
AndroidViewModel은 애플리케이션 컨텍스트가 필요할 때만 사용해야 합니다.
You should never store a reference of activity or a view that references a activity in the ViewModel.Because ViewModel is designed to outlive a activity and it will cause Memory Leak.
ViewModel 내에서 액티비티나 액티비티를 참조하는 뷰에 대한 참조를 저장해서는 안 됩니다. ViewModel은 액티비티의 수명보다 길게 설계되었기 때문에 이러한 참조는 메모리 누수를 발생시킬 수 있습니다.
출처 : https://stackoverflow.com/questions/44148966/androidviewmodel-vs-viewmodel
'개발 > 안드로이드' 카테고리의 다른 글
Manifest Merger failed 오류 수정하기 (0) | 2022.12.22 |
---|---|
특정 앱의 '앱 권한' 화면 띄우기 (0) | 2022.12.21 |
Android: 이전 액티비티로 돌아가기 (0) | 2022.12.21 |
'package R does not exist' 오류 수정하기 (0) | 2022.12.21 |
Fragment에서 onBackPressed()를 구현하기 (0) | 2022.12.21 |