반응형
이 글은 단순히 Room을 이용하여 데이터를 DB에 넣고 DB의 변동을 감지하여 RecyclerView를 갱신하는 방법에 대한 글이다. Room 사용방법이나 RecyclerView 사용방법은 추후에 업로드할 예정이다.
build.gradle에 Lifecycle 관련 라이브러리 추가
// Lifecycle components
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
//noinspection LifecycleAnnotationProcessorWithJava8
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.2.0"
Room - DAO 부분에서 LiveData 추가
- 다음과 같이 해당 메서드의 리턴값을 LiveData로 설정함으로써 Observer로 변화를 감지할 수 있다.
MainActivity (RecyclerView가 있는 액티비티)
db!!.countryDao().countryLiveSelect().observe(this, androidx.lifecycle.Observer {
var covidInfoList: MutableList<CovidInfo> = mutableListOf()
for (name in it) {
covidInfoList.add(CovidInfo(name.countryName, 0, 0))
}
adapter = ListAdapter(this, covidInfoList)
recyclerView.adapter = adapter
})
- observe 안에 있는 it의 타입은 countryLiveSelect의 반환값인 LiveData 안에 있는 MutableList<Country>다.
- 실시간으로 해당 테이블의 변화를 감지하여 변화가 있을 시 observe 안의 코드가 실행이 된다.
- RecyclerView에 반영하기 위해 데이터를 가공한 후 Adapter에 데이터를 넣어준다.
결과
반응형