Android (안드로이드)/Lifecycle
Android in A..Z - Lifecycle (Scope)
강태종
2021. 3. 24. 10:50
ViewModelScope
ViewModel마다 존재하는 Scope이다. ViewModel이 삭제되면 자동으로 취소된다.
class ExampleViewModel : ViewModel() {
init {
viewModelScope.launch {
/*
ViewModel이 사라지면 종료된다.
*/
}
}
}
LifeCycleScope
LifeCycle 객체마다 존재하는 Scope이다. Create, Start, Resume 3가지의 Mode를 지원하고 Active상태(화면에 보이는 상태)일 때만 수행된다.
class CoroutineFragment : BaseFragment<FragmentCoroutineBinding>(R.layout.fragment_coroutine) {
private var count = 0
private val logList by lazy { ArrayList<String>() }
private val logAdapter by lazy { LogAdapter().apply { submitList(logList) } }
override fun init() {
initCoroutine()
initSupportActionbar()
initRecyclerView()
initOnNavigate()
}
private fun initCoroutine() {
viewLifecycleOwner.lifecycleScope.launch {
whenCreated {
writeLog("${SimpleDateFormat.getTimeInstance().format(System.currentTimeMillis())} launch - launchWhenCreated")
}
whenStarted {
writeLog("${SimpleDateFormat.getTimeInstance().format(System.currentTimeMillis())} launch - launchWhenStarted")
}
whenResumed {
writeLog("${SimpleDateFormat.getTimeInstance().format(System.currentTimeMillis())} launch - launchWhenResumed")
}
}
viewLifecycleOwner.lifecycleScope.launchWhenCreated {
writeLog("${SimpleDateFormat.getTimeInstance().format(System.currentTimeMillis())} launch - launchWhenCreated(${count++})")
}
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
writeLog("${SimpleDateFormat.getTimeInstance().format(System.currentTimeMillis())} launch - launchWhenStarted(${count++})")
}
viewLifecycleOwner.lifecycleScope.launchWhenResumed {
while (true) {
writeLog("${SimpleDateFormat.getTimeInstance().format(System.currentTimeMillis())} launch - launchWhenResumed(${count++})")
delay(1000L)
}
}
}
private fun initSupportActionbar() {
setSupportActionBar(binding.toolbar)
}
private fun initRecyclerView() {
with(binding.recyclerView) {
adapter = logAdapter
}
}
private fun initOnNavigate() {
binding.setOnNavigate {
findNavController().navigate(CoroutineFragmentDirections.actionCoroutineFragmentToCoroutineNextFragment())
}
}
private fun writeLog(log: String) {
logList.add(log)
logAdapter.notifyItemInserted(logList.lastIndex)
}
}