https://codelabs.developers.google.com/codelabs/kotlin-android-training-live-data/index.html?index=..%2F..android-kotlin-fundamentals#7

이를 읽으면서 생각하게 된 내용을 정리한다.

https://developer.android.com/topic/libraries/architecture/viewmodel

ViewModel의 수명 주기

ViewModel 객체의 범위는 ViewModel을 가져올 때 ViewModelProvider에 전달되는 Lifecycle로 지정됩니다. ViewModel은 범위가 지정된 Lifecycle이 영구적으로 경과될 때까지, 즉 활동에서는 활동이 끝날 때까지 그리고 프래그먼트에서는 프래그먼트가 분리될 때까지 메모리에 남아 있습니다.

.

.

.

https://medium.com/@BladeCoder/ondetach-has-a-misleading-name-it-is-not-called-when-you-detach-a-fragment-using-d96a2fec90b5#:~:text=detach()%20%2C%20but%20only%20when,%2C%20onViewCreated()%20%2C%20onActivityCreated()%20.

Fragment의 수명주기

onDetach() has a misleading name, it is not called when you detach a fragment using FragmentTransaction.detach(), but only when the fragment is definitely removed from its containing activity as you can see in the horrific fragments lifecycle illustration.

.

.

.

나의생각)

ViewModel이 Fragment에서 생성되서 variable에 assign 되어 있는 경우 fragment가 없어질때까지 ViewModel의 수명이 유지 된다고 이해했다. 또한 fragment의 경우 fragment가 생성된 activity의 수명주기 까지 그 수명이 유진된다. 그렇다면 ViewModel에서 만들어진 LiveData의 생명주기도 fragment와 동일하게 되고 또 activity의 주기가 유질 될때 까지 유지된다. 

또한 그렇다면 하나의 activity에서 여러개의 fragment를 이용해 개발하는 경우 ViewModel간의 LiveData 의 수명주기가 같고 각 ViewModel간에 교차 사용가능하게 된다. 또한 observer를 이용 실시간 업데이트가 될수 있다.

===========================================================

===========================================================

위와 같이 생각했었지만 사실은 아니었다. 아래 참조
https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing

Share data between fragments

It’s very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of master-detail fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item. This case is never trivial as both fragments need to define some interface description, and the owner activity must bind the two together. In addition, both fragments must handle the scenario where the other fragment is not yet created or visible.

This common pain point can be addressed by using ViewModel objects. These fragments can share a ViewModel using their activity scope to handle this communication, as illustrated by the following sample code:

KOTLIN

JAVA

class SharedViewModel : ViewModel() {
   val selected = MutableLiveData<Item>()

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

class MasterFragment : 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
       })
   }
}

Notice that both fragments retrieve the activity that contains them. That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.

This approach offers the following benefits:

  • The activity does not need to do anything, or know anything about this communication.
  • Fragments don’t need to know about each other besides the SharedViewModel contract. If one of the fragments disappears, the other one keeps working as usual.
  • Each fragment has its own lifecycle, and is not affected by the lifecycle of the other one. If one fragment replaces the other one, the UI continues to work without any problems.

Comments are closed.

Post Navigation