-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoroutineTask.kt
More file actions
62 lines (46 loc) · 1.69 KB
/
CoroutineTask.kt
File metadata and controls
62 lines (46 loc) · 1.69 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.asutosh.util.coroutine
import kotlinx.coroutines.*
abstract class CoroutineTask<Params, Progress, Result> {
/* AsyncTask has been deprecated from Android 11
*
* CoroutineTask is a Utility class, if you want to seamlessly update your AsyncTasks to Coroutines.
* You don't need to change anything in your AsyncTask methods, parameters or logic.
* It Doesn't matter if your classes are in Java or Kotlin.
*/
private val uiScope = CoroutineScope(Dispatchers.Main)
private val backgroundScope = CoroutineScope(Dispatchers.Default)
private var result: Result? = null
protected abstract fun onPreExecute()
protected abstract fun doInBackground(vararg params: Params?): Result
protected abstract fun onPostExecute(result: Result?)
protected open fun onCancelled(){}
protected open fun onProgressUpdate(progress: Progress?) {}
fun execute(vararg params: Params) {
uiScope.launch {
uiScope.launch {
onPreExecute()
var result = backgroundScope.async {
doInBackground(*params)
}
uiScope.launch {
onPostExecute(result.await())
}
}
}
}
fun cancel(hasToCancel: Boolean){
if(hasToCancel){
uiScope.cancel("coroutine cancelled by user")
backgroundScope.cancel("coroutine cancelled by user")
uiScope.launch {
onPostExecute(null)
onCancelled()
}
}
}
protected fun publishProgress(progress: Progress) {
uiScope.launch{
onProgressUpdate(progress)
}
}
}