Android Jetpack

Android Room - 5 (Room + ViewModel + ViewModelScope + LiveData)

개복치 개발자 2022. 1. 27. 22:18

 개복치개발자 강의는 아래의 링크에서 확인할 수 있습니다.

 

개복치개발자 | Linktree

uyalae@naver.com

linktr.ee

 

 Room을 이전에 배운 ViewModel과 LiveData를 이용해서 함께 사용해보도록 하겠습니다.

 

 여기에서 ViewModelScope와 AndroidViewModel이라는 친구가 나옵니다. 간단하게 설명드리고 가면

 

 ViewModelScope 이 부분은 코루틴을 할 때 설명드리긴 할 것인데, 쉽게 말하면 ViewModel을 코루틴과 결합하여 사용하는 것입니다.

 (코루틴은 rx를 해보셨다면, rxjava와 유사한 친구로 이해하시면 될 것 같고, 아니면 그냥 비동기 작업을 해주는 쓰레드 정도로 알고 계셔도 될 것 같습니다.)

 

 그리고 AndroidViewModel은 구글링을 조금 해서 찾아보면 아래와 같이 나옵니다.

 

AndroidViewModel provides 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).

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.

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.

 

AndroidViewModel은 애플리케이션 컨텍스트를 제공합니다.
Viewmodel 내부에서 컨텍스트를 사용해야 하는 경우 애플리케이션 컨텍스트가 포함되어 있기 때문에 AndroidViewModel(AVM)을 사용해야 합니다. 컨텍스트 호출 getApplication()을 검색하려면 그렇지 않으면 일반 ViewModel(VM)을 사용하십시오.

AndroidViewModel에는 애플리케이션 컨텍스트가 있습니다. 메모리 누수를 일으킬 수 있으므로 정적 컨텍스트 인스턴스를 갖는 것이 나쁘다는 것을 우리 모두 알고 있습니다!! 그러나 실행 중인 애플리케이션에 애플리케이션 인스턴스가 하나만 있기 때문에 정적 애플리케이션 인스턴스를 갖는 것이 생각만큼 나쁘지 않습니다.

따라서 특정 클래스에서 Application 인스턴스를 사용하고 갖는 것은 일반적으로 문제가 되지 않습니다. 그러나 Application 인스턴스가 이들을 참조한다면 참조 주기 문제로 인해 문제가 된다.

 

 싱글톤을 공부해보셨다면, 이 것이 쉽게 와 닿으실 것 같지만, 만약 싱글톤에 대해서 잘 모르신다면 아래의 글을 참고해보세요.

https://tecoble.techcourse.co.kr/post/2020-11-07-singleton/

 

싱글톤(Singleton) 패턴이란?

이번 글에서는 디자인 패턴의 종류 중 하나인 싱글톤 패턴에 대해 알아보자. 싱글톤 패턴이 무엇인지, 패턴 구현 시 주의할 점은 무엇인지에 대해 알아보는 것만으로도 많은 도움이 될 것이라

tecoble.techcourse.co.kr

 

 우선은 아래와 같은 것을 만들어보기 위해 코드를 작성해봤습니다.

 

 

 insert를 누르면 Room에 데이터가 들어가고, LiveData로 데이터를 관찰해서 변경된 데이터들을 보이도록 설계해봤습니다.

 

 코드는 아래와 같습니다.

 

 gradle에 아래의 부분을 추가하고

 

// ROOM
def roomVersion = "2.4.0"

implementation("androidx.room:room-runtime:$roomVersion")
annotationProcessor("androidx.room:room-compiler:$roomVersion")

// To use Kotlin annotation processing tool (kapt)
kapt("androidx.room:room-compiler:$roomVersion")

implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0")

 

 전체 gradle은 아래와 같습니다.

 

 

 그리고 나머지 코드는 아래와 같습니다.

 

 

 

 

 

 

 - 참조

 

https://developer.android.com/topic/libraries/architecture/coroutines?hl=ko 

 

수명 주기 인식 구성요소와 함께 Kotlin 코루틴 사용  |  Android 개발자  |  Android Developers

수명 주기 인식 구성요소와 함께 Kotlin 코루틴 사용 Kotlin 코루틴은 비동기 코드를 작성할 수 있게 하는 API를 제공합니다. Kotlin 코루틴을 사용하면 코루틴이 실행되어야 하는 시기를 관리하는 데

developer.android.com

 

https://developer.android.com/codelabs/android-room-with-a-view-kotlin?hl=ko#17 

 

뷰를 사용한 Android Room - Kotlin  |  Android 개발자  |  Android Developers

이 Codelab에서는 Kotlin 코루틴과 함께 Android 아키텍처 구성요소(RoomDatabase, Entity, DAO, AndroidViewModel, LiveData)를 사용하는 Android 앱을 Kotlin으로 빌드합니다. 이 샘플 앱은 단어 목록을 Room 데이터베이스

developer.android.com