안드로이드(Android)/코틀린(Kotlin)
DialogFragment lifecycleScope 사용시 주의점
리안94
2021. 12. 15. 15:01
다이얼로그 프래그먼트에서 아무생각없이 일반 프래그먼트와 동일하게 lifecycleScope를 이용했었더니 다음과 같은 문제가 발생하였다.
이 현상은 싱글톤으로 다이얼로그 프래그먼트를 생성하게되면 나타나는 문제이다.
@AndroidEntryPoint
class TestDialogFragment : DialogFragment() {
...
init {
lifecycleScope.launch {
whenResumed {
//초기세팅
}
whenCreated {
//초기 값 세팅
}
}
}
}
di(hilt)를 이용해 다이얼로그를 싱글톤으로 생성해주는데, 첫 1회는 해당 lifecycleScope는 잘 동작하지만, 두번째 부터는 해당구문은 타지않는다.
이 문제를 해결하기위해서는 init에서 설정할 것이 아닌 onCreateView에서 설정해주어야한다. 또한 fragment의 lifecycleScope를 이용하는 것이 아닌 viewLifecycleOwner의 lifecycleScope를 이용해주어야한다.
이유로는 프래그먼트는 파괴되지않고, 뷰만 재생성되기 때문이다.
@AndroidEntryPoint
class TestDialogFragment : DialogFragment() {
...
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewLifecycleOwner.lifecycleScope.launch {
whenResumed {
//초기 설정
}
whenCreated {
//초기 값 설정
}
}
return super.onCreateView(inflater, container, savedInstanceState)
}
}