Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- cloudwatch
- amazonqcli
- sns
- kubernetes
- fcm
- aws
- IaC
- lambda
- 병목
- Validation
- serverless
- CHECK
- rds
- SageMaker
- Lamda
- terraform
Archives
- Today
- Total
잡다한 IT 지식
03. 코루틴 suspend 함수 본문
suspend 함수는 코루틴 내에서 불리거나 혹은 같은 suspend 함수 내에서만 호출 될 수 있습니다.
package com.goodee.test
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.databinding.DataBindingUtil
import com.goodee.test.databinding.ActivityMainBinding
import kotlinx.coroutines.*
class MainActivity : AppCompatActivity() {
private val TAG: String = "로그"
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
val startTime = System.currentTimeMillis()
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.nextBtn.setOnClickListener {
val startTime = System.currentTimeMillis()
CoroutineScope(Dispatchers.IO).launch {
// 현재 코루틴을 3초간 멈춘 후에 출력함.
Log.d(TAG,"MainActivity - ${doNetworkCall1()} time : ${System.currentTimeMillis() - startTime}")
// 이전 과정이 끝나고 5초 멈춘 후에 출력함.
Log.d(TAG,"MainActivity - ${doNetworkCall2()} time : ${System.currentTimeMillis() - startTime}")
}
}
}
// 3초가 걸리는 suspend 함수1
suspend fun doNetworkCall1(): String {
delay(3 * 1000L)
return "answer1"
}
// 6초가 걸리는 suspend 함수2
suspend fun doNetworkCall2(): String {
delay(5 * 1000L)
return "answer2"
}
}
첫번째 suspend 함수와 두번째 suspend 함수는 같은 코루틴 내에 있으므로 delay 함수가 서로에게 영향을 준다.
따라서, 출력 결과는 3초에 한 번. 8(3+5)초에 한 번 일어난다.
'컴퓨터 언어 > Kotlin' 카테고리의 다른 글
05. 코루틴의 runBlocking (0) | 2022.07.05 |
---|---|
04. 코루틴의 Context (0) | 2022.07.05 |
02. 코루틴 첫 시작 (0) | 2022.07.04 |
01. 코루틴이란 무엇인가? (0) | 2022.06.27 |
코루틴 관련해서 좋은 블로그 (0) | 2021.08.31 |