반응형
AsyncTask가 Deprecate 되고 대응 방법으로 몇 가지가 있지만 간단하게 변경하는 방법입니다.
아직 코루틴에 대한 공부가 부족해 최적화가 되어 있진 않지만 기존 asynctask를 사용하시던 분들이 쉽게 이해하실수 있게
작성 해 봤습니다.
private class SampleAsync extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... voids) {
return "결과 스트링값";
}
@Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
}
}
// 실행
new SampleAsync().execute();
형태는 다들 다르게 쓰셨겠지만 위와 같은 기본형으로 되어 있을 겁니다.
class SampleCoroutine(private val coroutineResult: CoroutineResult) : CoroutineScope {
private val backgroundDispatcher: CoroutineDispatcher = Dispatchers.IO
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
fun cancel() {
job.cancel()
}
fun execute() {
launch(coroutineContext) {
onPreExecute()
val result: String = doInBackground()
onPostExecute(result)
}
}
private fun onPreExecute() {
}
private suspend fun doInBackground(): String = withContext(backgroundDispatcher) {
var result = ""
// 백그라운드 기능 실행
result
}
private suspend fun onPostExecute(result: String) = withContext(Dispatchers.Main) {
when (result) {
"" -> {
coroutineResult.error(result)
}
else -> {
coroutineResult.success(result)
}
}
}
}
// 인터페이스
interface CoroutineResult {
fun success(result: String)
fun error(error: String)
}
// 실행
SampleCoroutine(object : CoroutineResult{
override fun success(result: String) {}
override fun error(error: String) {}
}).execute()
조금씩 커스텀 해서 사용하시면 좋을 것 같습니다.
'Kotlin programming > 코틀린(kotlin)' 카테고리의 다른 글
[Kotlin][Naver login 구현] 앱이 설치돼있지 않을 때 로그인 시도 시 발생하는 에러 (0) | 2022.01.28 |
---|---|
[Kotlin] 키보드 내리기 Hide keyboard (0) | 2022.01.27 |
[Kotlin] JCenter 서비스 업데이트로 인한 mavenCentral 전환 이슈(Migration Jcenter to mavenCentral) (0) | 2022.01.18 |
[Kotlin] ONE UI 4.0 업데이트 하고 나서 앱이 사라 졌다! ㅠㅠ (0) | 2022.01.04 |
[Android studio]안드로이드 스튜디오 SDK 오류 : 실제 기기에서 실행 안됨 에러 (0) | 2021.12.31 |