Coroutine이란?
특징
배경

의존성 추가
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9")
코루틴의 주요개념
코루틴 스코프(Coroutine Scope)
// 메인 쓰레드에서 실행될 사용자 정의 Scope
val scope = CoroutineScope(Dispatchers.Main)
scope.launch {
// 메인 쓰레드 작업
}
// 백그라운드에서 실행될 사용자 정의 Scope
CoroutineScope(Dispatchers.IO).launch {
// 백그라운드 작업
}
// 앱의 라이프사이클동안 실행될 Scope
GlobalScope.launch {
// 백그라운드로 전환하여 작업
launch(Dispatchers.IO) {
}
// 메인쓰레드로 전환하여 작업
launch(Dispatchers.Main) {
}
}
class MyViewModel: ViewModel() {
init {
viewModelScope.launch {
// ViewModel이 제거되면 코루틴도 자동으로 취소됩니다.
}
}
}
class MyActivity : AppCompatActivity() {
init {
lifecycleScope.launch {
// Lifecycle이 끝날 때 코루틴 작업이 자동으로 취소됩니다.
}
}
}
CoroutineContext
val job = CoroutineScope(Dispatchers.IO).launch {
// 비동기 작업
}
job.join() // 작업이 완료되기까지 대기
job.cancel() // 작업 취소
val job1 = Job()
CoroutineScope(job1 + Dispatchers.Main).launch {
// 메인 쓰레드 작업
launch(Dispatchers.IO) {
// 비동기 작업
}
withContext(Dispatchers.Default) {
// 비동기 작업
}
}
val job2 = CoroutineScope(Dispatchers.IO).launch {
// 비동기 작업
}
job1.cancel() // job1이 연결된 코루틴 작업 취소
Dispatchers
CoroutineBuilder
CoroutineScope(Dispatchers.Main).launch {
// 결과값이 필요없는 작업
}
val deferred = CoroutineScope(Dispatchers.Main).async {
// 결과값
"Hello Coroutine!"
}
val message = deferred.await() // await()함수로 결과값 반환
println(message)
init {
viewModelScope.launch { // Dispatchers.Main
val user = getUserInfo() // Dispatchers.Main
}
}
suspend fun getUserInfo(): User = // Dispatchers.Main
withContext(Dispatchers.IO) { // Dispatchers.IO
val response = apiService.getUserInfo() // Dispatchers.IO
if (response.isSuccessful) { // Dispatchers.IO
return@withContext response.body() // Dispatchers.IO
} else { // Dispatchers.IO
return@withContext null // Dispatchers.IO
} // Dispatchers.IO
} // Dispatchers.Main
cancel
val job = CoroutineScope(Dispatchers.Default).launch {
val job1 = launch {
for (i in 0..10){
delay(500)
Log.d("코루틴","$i")
}
}
}
-> 아래 코드에서 job을 캔슬하게 되면 안에 있던 job1도 중단됩니다.
delay
join
CoroutineScope(Dispatchers.Default).launch {
launch {
for (i in 0..5) {
delay(500)
}
}.join()
launch {
for (i in 6..10) {
delay(500)
}
}
}
}
async로 결과값 처리
CoroutineScope(Dispatchers.Default).async {
val deferred1 = async {
delay(500)
350
}
val deferred2 = async {
delay(1000)
200
}
Log.d("coroutine","${deferred1.await() + deferred2.await()}")
}
}
suspend 함수
suspend fun subRoutine() {
for(i in 0..10) {
Log.d("subRoutine","$i")
}
}
CoroutineScope(Dispatchers.Main).launch {
//선처리 코드
subroutine()
//후처리 코드
}
withContext
suspend fun main() {
val deferred: Deferred<String> = CoroutineScope(Dispatchers.IO).async {
"Async Result"
}
val result = deferred.await()
println(result)
-> Deferred로 결과값을 감싼 다음 await() 메서드를 통해 해당 값이 수신될 때까지 기다려야 한다.
suspend fun main() {
val result: String = withContext(Dispatchers.IO) {
"Async Result"
}
println(result)
}
(참고 블로그 : https://greedy0110.tistory.com/102)
https://0391kjy.tistory.com/49