본문 바로가기

Study/Android

CoroutineScope Network Example

import android.util.Log
import kotlinx.coroutines.*

/**
 * async task -> coroutine scope
 *
 * @param Result
 * @constructor Create empty Coroutine task async
 */
abstract class CoroutineTaskAsync<Result> {

    private var coroutineScope: CoroutineScope? = null

    open fun execute() {
        coroutineScope?.cancel()
        coroutineScope = MainScope()
        coroutineScope?.launch(errorHandler) {
            onReady()
            try {
                val defer = async(Dispatchers.IO) {
                    Log.i("task", "Async Fetch Started")
                    onRunning()
                }
                val result = defer.await()
                onResult(result)
            } catch (e: CancellationException) {
                Log.i("task", "Async Cancel Result")
            }
        }
    }

    abstract suspend fun onReady()

    abstract suspend fun onRunning(): Result

    abstract suspend fun onResult(result: Result)

    open fun onCancel() {
        if (coroutineScope?.isActive == true) {
            coroutineScope?.cancel()
        }
    }

    private val errorHandler = CoroutineExceptionHandler { context, error ->
        coroutineScope?.launch(Dispatchers.Main) {
            Log.i("task", "Async Exception Result")
        }
    }
}

 

AsyncTask 처럼 비슷하게 쓸 수 있음

 

 

 

 

 

참조 : https://github.com/elye/demo_android_coroutine_network_fetch

 

'Study > Android' 카테고리의 다른 글

미디어 스토어 사진 가져오는 쿼리  (0) 2021.11.30
앱 서명 jks -> pepk  (0) 2021.11.10
Kotlin SingleTon with Fragment  (0) 2021.10.06
[공유] RecycleView Animation  (0) 2021.08.23
DataBinding  (0) 2021.08.19