개발 일기

coroutine ktx 본문

Client/안드로이드

coroutine ktx

이건욱

coroutine는 비동기를 보다 쉽게 작성할수 있는 API 제공합니다.

 

ktx 종속성 추가

ViewModelScope에서는 androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01 이상을 사용하세요.
LifecycleScope에서는 androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01 이상을 사용하세요.
liveData에서는 androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01 이상을 사용하세요.

 

ViewModel Scope

 

viewModelScope을 사용하면 ViewModel onClear() 됬을 때 자동적으로 취소가 됩니다.

 

class MyViewModel: ViewModel() {
        init {
            viewModelScope.launch {
                // Coroutine that will be canceled when the ViewModel is cleared.
            }
        }
    }

 

LifecycleScope

 

LifecycleScope는 각 Lifecycle 개체에서 정의됩니다.

따라서 Lifecycle이 끝날 때 취소됩니다.

 

접근은 :)

class MyFragment: Fragment() {
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            viewLifecycleOwner.lifecycleScope.launch {
                val params = TextViewCompat.getTextMetricsParams(textView)
                val precomputedText = withContext(Dispatchers.Default) {
                    PrecomputedTextCompat.create(longTextContent, params)
                }
                TextViewCompat.setPrecomputedText(textView, precomputedText)
            }
        }
    }
    

 

lifecycleScope에 따라 결정할수 있습니다.

 

아래의 예시는 STARTED 상태일때는 실행되는 코드입니다.

class MyFragment: Fragment {
        init { // Notice that we can safely launch in the constructor of the Fragment.
            lifecycleScope.launch {
                whenStarted {
                    // The block inside will run only when Lifecycle is at least STARTED.
                    // It will start executing when fragment is started and
                    // can call other suspend methods.
                    loadingView.visibility = View.VISIBLE
                    val canAccess = withContext(Dispatchers.IO) {
                        checkUserAccess()
                    }

                    // When checkUserAccess returns, the next line is automatically
                    // suspended if the Lifecycle is not *at least* STARTED.
                    // We could safely run fragment transactions because we know the
                    // code won't run unless the lifecycle is at least STARTED.
                    loadingView.visibility = View.GONE
                    if (canAccess == false) {
                        findNavController().popBackStack()
                    } else {
                        showContent()
                    }
                }

                // This line runs only after the whenStarted block above has completed.

            }
        }
    }

 

코루틴이 when 메서드 중 하나를 통해 활성 상태인 동안 Lifecycle이 끝나면 그 코루틴은 자동으로 취소됩니다. 아래 예에서 Lifecycle 상태가 DESTROYED이면 finally 블록이 실행됩니다.

class MyFragment: Fragment {
        init {
            lifecycleScope.launchWhenStarted {
                try {
                    // Call some suspend functions.
                } finally {
                    // This line might execute after Lifecycle is DESTROYED.
                    if (lifecycle.state >= STARTED) {
                        // Here, since we've checked, it is safe to run any
                        // Fragment transactions.
                    }
                }
            }
        }
    }

 

LiveData를 사용할 때 값을 비동적으로 계산해야 할 수 있습니다.

val user: LiveData<User> = liveData {
        val data = database.loadUser() // loadUser is a suspend function.
        emit(data)
    }
    
 
 
 
 

'Client > 안드로이드' 카테고리의 다른 글

Transformations LiveData  (0) 2020.04.04
다중 창 지원  (0) 2020.04.03
Fragment recyclerView 관련 메모리 이슈  (0) 2020.03.27
ViewModel  (0) 2020.03.27
Rxjava Subject  (0) 2020.03.26
Comments