Coroutine은 다양한 테스크를 진행할 때 필요한 요소이다.
스레드(Thread)와 햇갈릴 수 있는데 스레드와 다른 점은
dependencies {
// coroutine
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.3")
implementation(libs.androidx.core.ktx)
}
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// 화면 그려주는 코드
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val TAG = "MainActivity";
GlobalScope.launch {
// 1초후 실행
delay(1000L)
Log.d(TAG, "thread1 ${Thread.currentThread().name}")
}
Log.d(TAG, "thread2 ${Thread.currentThread().name}")
}
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// 화면 그려주는 코드
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val TAG = "MainActivity";
GlobalScope.launch(Dispatchers.Main) {
Log.d(TAG,"1")
delay(3000L)
Log .d(TAG, "Coroutine says hello from thread1 ${Thread.currentThread().name}")
Log.d(TAG, "2")
doNetworkCall()
Log.d(TAG, "3")
doNetworkCall2()
Log.d(TAG, "4")
}
Log.d(TAG, "5")
}
//suspend function 활용
suspend fun doNetworkCall():String{
delay(1000L)
return "this is the answer"
}
suspend fun doNetworkCall2(): String{
delay(2000L)
return "this is the answer"
}
2024-05-05 12:20:51.123 10245-10245 MainActivity com.sangmoki.bts_photo D 5
2024-05-05 12:20:51.129 10245-10245 MainActivity com.sangmoki.bts_photo D 1
2024-05-05 12:20:51.179 10245-10264 OpenGLRenderer com.sangmoki.bts_photo E Unable to match the desired swap behavior.
2024-05-05 12:20:51.719 10245-10245 WindowOnBackDispatcher com.sangmoki.bts_photo W sendCancelIfRunning: isInProgress=falsecallback=android.view.ViewRootImpl$$ExternalSyntheticLambda17@482f0b1
2024-05-05 12:20:54.133 10245-10245 MainActivity com.sangmoki.bts_photo D Coroutine says hello from thread1 main
2024-05-05 12:20:54.133 10245-10245 MainActivity com.sangmoki.bts_photo D 2
2024-05-05 12:20:55.135 10245-10245 MainActivity com.sangmoki.bts_photo D 3
2024-05-05 12:20:55.768 10245-10281 ProfileInstaller com.sangmoki.bts_photo D Installing profile for com.sangmoki.bts_photo
2024-05-05 12:20:57.136 10245-10245 MainActivity com.sangmoki.bts_photo D 4
2024-05-05 12:21:24.356 10245-10255 gmoki.bts_photo com.sangmoki.bts_photo W Cleared Reference was only reachable from finalizer (only reported once)
Dispatchers.Main - 메인 쓰레드에서 사용하게 되고, UI 관련 작업을 할 때 사용한다.
Dispatchers.IO - 네트워크 작업에서 사용하며, 데이터를 쓰고 읽는데 적합하다.
Dispatchers.Default - 계산이 많이 필요할 때 유용하다. 예를들어 10000개의 계산이 필요하면 다른 쓰레드를 방해하지 않고 계산할 수 있게 한다.
Dispatchers.Unconfined - 제한되지 않는다.
// Dispatcher는 Main, IO, Default, Unconfined 등으로 변경이 가능하다.
GlobalScope.launch(Dispatchers.Main) {
}
GlobalScope.launch(newSingleThreadContext("My Thread")) {}
GlobalScope.launch(Dispatchers.IO) { //네트워크에서 불러올 데이터
Log.d(TAG,"1")
val answer = doNetworkCall() //이 함수를 보면 3초 delay가 있기때문에 3초뒤에 dispatcherMain 스레드를 실행하게 된다.
withContext(Dispatchers.Main){ //now this thread will run main thread
Log.d(TAG, "2")
TextView.text = answer
}
}
//doNetwork Call()은 delay예시에서 사용했던 suspend function다.
suspend fun doNetworkCall():String{
delay(3000L)
return "this is the answer"
}