Android : ViewModel

cad·2022년 1월 4일
0

Android

목록 보기
3/4

사용 이유: UI와 로직의 분리

  • 메인 UI에서 모든 업무를 감당하기에는 무리가 있다.
  • UI를 관리하고 데이터 통신을 모두 Activity나 Fragment에서 하면 코드도 복잡해지고 Lifecycle 관리나 성능 저하를 면치 못할 것이다.
  • ViewModel 사용을 통해 UI와 로직 분리를 설계한다.

ViewModel : 안드로이드 공식 문서

Android 공식 지원

  • ViewModel은 안드로이드에서 공식적으로 지원하는 Android Jetpack 의 구성요소 중 하나이다.
  • 공식 문서를 보면 자세히 알 수 있지만 처음 공부하는 입장에서는 구현 단계에서 되게 골치 아팠었다.

구현

// 프래그먼트간 데이터 공유
class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

class ListFragment : Fragment() {

    private lateinit var itemSelector: Selector

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        itemSelector.setOnClickListener { item ->
            // Update the UI
        }
    }
}

class DetailFragment : Fragment() {

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
            // Update the UI
        })
    }
}
  • ViewModel은 데이터의 변경 사항을 알려주기 위해 LiveData를 사용한다.
  • Activity 에 붙여진 여러 Fragment 간에 데이터 공유가 필요할 수도 있다. 위 코드는 두 프래그먼트에서 한 ViewModel에 접근하도록 설계되었다.

Coroutine : 안드로이드 공식 문서

ViewModel과 Coroutine

  • Kotlin 코루틴은 비동기 코드를 작성할 수 있게하는 API를 제공한다.
  • 서버와 통신을 하는 등, 다양한 이유도 비동기 작업은 거의 필수적인데 여기서 Coroutine 이 많이 사용되고 있다.

ViewModelScope

class MyViewModel: ViewModel() {
    init {
        viewModelScope.launch {
            // ViewModel이 삭제되면 코루틴도 같이 사라진다.
        }
    }
}
  • viewModelScope를 사용하면 알아서 뷰모델이 없어지기 전까지 유지되다 뷰모델이 clear되면 같이 종료한다.
profile
Dare mighty things!

0개의 댓글