일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- ConstraintLayout
- list
- 생명주기
- map
- enum
- union
- docker-compose
- MINUS
- class component
- CLASS
- mongoose
- ReactNative
- Foreign Key
- recyclerview
- Kotlin
- Swift
- Filter
- Generic
- vuex
- animation
- react native
- collection
- function
- Interface
- lifecycle
- AWS
- Service
- LiveData
- docker
- elementAt
- Today
- Total
개발 일기
LiveData ? 본문
LiveData 란?
LiveData는 식별 가능한 데이터 홀더 클래스입니다.
일반 클래스와는 달리 앱 구성요소인 수명주기를 고려합니다.
이러한 방식으로 통해 수명 주기에 있는 상태에 있는 관찰자만 업데이트를 진행합니다.
LiveData는 Observer 클래스 수명주기가 STARTED , RESUMED 일 경우에만 활성 상태에 있습니다.
LiveData는 LifecycleOwner을 구현한 관찰자를 등록 할수 있습니다.
이 관계를 통해서 DESTROYED 변경 될 때 관찰자를 삭제 할수 있습니다.
따라서 안전하게 관찰 할수 있으며 , 수명 주기가 끝나는 순간 해제되어 누출을 막을수가 있습니다.
이점 :)
UI와 데이터 상태의 일치 보장
- Observer 객체의 UI을 업데이트를 할수 있습니다.
메모리 누출 없음
- 수명 주기가 끝나면 자동적으로 삭제 됩니다.
중지된 활동으로 인한 비정상 종료 없음
- 수명 주기가 비 활성화 상태에 있으면 어떤 이벤트도 받지 않습니다.
수명 주기를 더 이상 수동으로 처리할 필요 없음
- UI 구성요소는 관련 데이터를 관찰하기만 하며 관찰을 중지하거나 재개하지 않습니다. LiveData는 관찰하는 동안 관련 수명 주기 상태의 변경을 인식하므로 이 모든 것을 자동으로 관리합니다.
항상 최신 데이터 유지
- 수명 주기가 비활성화되었다면 다시 활성화될 때 최신 데이터를 받습니다. 예를 들어 백그라운드에 있었던 활동은 포그라운드로 돌아온 직후 최신 데이터를 받습니다.
적절한 구성 변경
- 기기 회전과 같은 구성 변경으로 인해 활동 또는 프래그먼트가 다시 생성되면, 사용 가능한 최신 데이터를 즉시 받게 됩니다.리소스 공유싱글톤 패턴을 사용하는 LiveData 개체를 확장하여 시스템 서비스를 앱에서 공유하도록 래핑할 수 있습니다. LiveData 개체가 시스템 서비스에 한 번 연결되면 리소스가 필요한 모든 관찰자는 LiveData 개체를 바로 관찰할 수 있습니다. 자세한 내용은 LiveData 확장을 참조하세요.
사용 :)
class NameViewModel : ViewModel() {
// Create a LiveData with a String
val currentName: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
// Rest of the ViewModel...
}
일반적으로 LiveData는 ViewModel과 에 저장되며 이런 형식으로 만들수 있습니다.
ViewModel에서 하는 이유는 자세한 내용은 여기에서 확인 부탁드립니다.
간단하게는 데이터 상태를 View에서 관리를 하지 않기 위함입니다.
class NameActivity : AppCompatActivity() {
private lateinit var model: NameViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Other code to setup the activity...
// Get the ViewModel.
model = ViewModelProviders.of(this).get(NameViewModel::class.java)
// Create the observer which updates the UI.
val nameObserver = Observer<String> { newName ->
// Update the UI, in this case, a TextView.
nameTextView.text = newName
}
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
model.currentName.observe(this, nameObserver)
}
}
위와 같이 observe 라는 방식으로 관찰을 시작합니다.
button.setOnClickListener {
val anotherName = "John Doe"
model.currentName.setValue(anotherName)
}
Live Data는 데이터를 공개적으로 업데이트를 할수가 없습니다.
따라서 MutableLiveData 클래스를 통해서 setValue(T) , postValue(T)을 구현할수 있습니다.
일반적으로 ViewModel LiveData만 접근이 가능하도록 노출시킵니다.
setValue ( 메인 쓰레드에서만 불려야 합니다. )
= This method must be called from the main thread. If you need set a value from a background thread, you can use postValue(Object)
postValue ( 아래와 같이 두번 했을 때 b 가 나오고 그 다음에 a 가 나오게 됩니다. )
liveData.postValue("a");
liveData.setValue("b");
The value "b" would be set at first and later the main thread would override it with the value "a".
이 위에 내용 외에도 LiveData 확장 , LiveData 변환 ( 관찰자에게 전달하기전 값 변경 ) 할수 있습니다.
'Client > 안드로이드' 카테고리의 다른 글
Android Manifest ? (0) | 2020.03.21 |
---|---|
WorkManager ? (0) | 2020.03.18 |
Picasso , Glide , Fresco (0) | 2020.03.16 |
android 4대 구성요소? (0) | 2020.03.16 |
ImageView , AppCompatImageView 차이 ? (0) | 2020.03.14 |