Kotlin Study

Kotlin Coroutine 기본 동작 방식

85chong 2022. 4. 20. 16:56
728x90
반응형
SMALL
class TestActivity : AppCompatActivity() {

	val A = 67
	val B = 89

	suspend fun doSomethingUsefulOne(): Int {
		Log.d("LOG", "doSomethingUsefulOne start")
		delay(3000L)
		Log.d("LOG", "doSomethingUsefulOne end")
		return A
	}

	suspend fun doSomethingUsefulTwo(): Int {
		Log.d("LOG", "doSomethingUsefulTwo start")
		delay(3000L)
		Log.d("LOG", "doSomethingUsefulTwo end")
		return B
	}

	fun mainAsyncBasicA() = GlobalScope.launch {
		val time = measureTimeMillis {
			 val one = doSomethingUsefulOne()
			 val two = doSomethingUsefulTwo()
			 Log.d("LOG", "$A + $B 는 $${one+two} 입니다.")
		}
		Log.d("LOG", "Completed in ${time/1000}s")
	}

	fun mainAsyncBasicB() = GlobalScope.launch {
		val time = measureTimeMillis {
			val one = async {
				doSomethingUsefulOne()
			}
			val two = async {
				doSomethingUsefulTwo()
			}
			Log.d("LOG", "$A + $B 는 ${one.await() + two.await()} 이다.")
		}
		Log.d("LOG", "Completed in ${time/1000}s")
	}
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
	
	}		

}//class end

 

위의 코드에서 mainAsyncBasicA() 는 일반적으로 함수를 호출할때 방식임
mainAsyncBasicB()는 coroutine 을 이용한 아주 기본적인 동작 테스트임
위의 준비된 코드에서 일반적인 함수 호출을 하면

 

		...
		override fun onCreate(savedInstanceState: Bundle?) {
			super.onCreate(savedInstanceState)

			mainAsyncBasicA()
			
		}		
		...

 

 

아래와 같은 log 가 찍힘

...
doSomethingUsefulOne start
doSomethingUsefulOne end
doSomethingUsefulTwo start
doSomethingUsefulTwo end
67 + 89 는 $156 입니다.
Completed in 6s

 

 

위의 준비된 코드에서 coroutine 을 이용한 기본적이 함수 호출을 하면

		...
		override fun onCreate(savedInstanceState: Bundle?) {
			super.onCreate(savedInstanceState)

			mainAsyncBasicB()
			
		}		
		...

 

 

아래와 같은 log 가 찍힘

D/LOG: doSomethingUsefulOne start
D/LOG: doSomethingUsefulTwo start
D/LOG: doSomethingUsefulTwo end
D/LOG: doSomethingUsefulOne end
D/LOG: 67 + 89 는 156 이다.
D/LOG: Completed in 3s

 

위의 결과 같이 coroutine 을 사용하면 async를 통해 동시 수행 되므로, 시간이 더 빨라지는 결과를 볼 수 있음



- 끝 -