일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- Compose
- AWS
- architecture
- activity
- Hilt
- pandas
- textfield
- boj
- Python
- Codeforces
- ProGuard
- 프로그래머스
- androidStudio
- 코드포스
- 쿠링
- 암호학
- Coroutine
- TEST
- Rxjava
- android
- MyVoca
- 백준
- livedata
- Gradle
- MiTweet
- Coroutines
- Kotlin
- GitHub
- 코루틴
- relay
- Today
- Total
이동식 저장소
[Android] Application 범위에서 코루틴을 실행하고 싶다면 본문
아래의 글을 요약하였음을 밝힙니다.
Coroutines & Patterns for work that shouldn’t be cancelled
Cancellation and Exceptions in Coroutines (Part 4)
medium.com
코루틴은 자신의 scope가 종료될 때 같이 종료된다. 예를 들어 ``viewModelScope``에서 시작한 코루틴은 ``ViewModel``이 destroy되면 자신의 작업이 끝나지 않았더라도 종료된다.
종료되는 범위를 넓혀서 앱이 종료되기 전까지 종료되지 않는 코루틴을 실행하려면 ``Application``에 커스텀 scope를 정의하고, 정의한 scope를 코루틴을 실행할 객체에 inject하여 사용해야 한다.
class MyApplication : Application() {
val applicationScope = CoroutineScope(SupervisorJob() + ...)
}
이제 다음과 같이 코루틴을 실행하면 된다.
class Repository(
private val externalScope: CoroutineScope,
private val ioDispatcher: CoroutineDispatcher
) {
suspend fun doWork() {
withContext(ioDispatcher) {
doSomeOtherWork()
externalScope.launch {
veryImportantOperation()
}.join()
}
}
}
``externalScope``에 ``applicationScope``를 inject했다면, ``launch`` 블럭은 앱이 종료되지 않는 한 계속 실행된다. 설령 ``withContext(ioDispatcher)`` 코루틴이 종료되더라도 계속 실행된다.
별개로, 코루틴을 사용할 때는 위의 코드처럼 ``CorouineScope``와 ``CoroutineDispatcher``를 매개변수로 받아 사용하자. 코루틴을 테스트할 때는 ``TestCoroutineDispatcher`` 등의 객체를 사용하는데, Dispatcher를 하드 코딩하여 사용하면 테스트하기 어려워진다.
더 자세한 내용은 위의 글을 읽어보길 바란다. 글이 워낙 좋아서.
'Primary > Android' 카테고리의 다른 글
Android Architecture Layers - 1. Data (0) | 2022.06.15 |
---|---|
Android Architecture Layers - 0. Overview (1) | 2022.06.07 |
[Android] Baseline Profile wasn't successfully installed (1) | 2022.06.01 |
Android Studio에서 디바이스의 화면 캡쳐하기 (0) | 2021.09.29 |
Android에서 Vector Drawable 추가하기 (0) | 2021.06.29 |