-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathCoroutineFunExtends.kt
More file actions
91 lines (82 loc) · 2.3 KB
/
CoroutineFunExtends.kt
File metadata and controls
91 lines (82 loc) · 2.3 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package common.base
import android.os.Looper
import kotlinx.coroutines.*
/**
* @author fee
* <P>DESC:
* 针对 Kotlin 的 [Coroutine] 扩展函数
* </p>
*/
/**
* 执行代码块,可选为在工作线程中
* @param isExecuteOnWorkThread true: 在工作线程中执行;
* @param block 要执行的代码块
* @return Deferred 当且仅当在 工作线程中执行时还有该返回值,调用处可以再调用[Deferred#await()] 得到 [block]中的返回值
*/
fun <R> executeBlock(isExecuteOnWorkThread: Boolean, block: () -> R): Deferred<R>? {
return if (isExecuteOnWorkThread) {
CoroutineScope(Dispatchers.Default).async {
block()
}
} else{
val s = block()
null
}
}
/**
* 将在UI线程中执行代码块
* @param block 要执行的代码块
*/
fun <R> executeBlockOnUiThread(block: () -> R){
val isAlreadyOnMainThread = Looper.getMainLooper() == Looper.myLooper()
if (isAlreadyOnMainThread) {
block()
return
}
MainScope().launch {
block()
}
}
/**
*
*/
fun <R> executeBlockOnUiThreadAlways(block: () -> R) {
MainScope().launch {
block()
}
}
/**
* @param isExecuteOnThreadOrUiThread true:将运行在工作线程;false:将运行的UI线程
* @param block 将运行的代码块
* @return [R] 所运行的代码块将返回的结果类型
*/
fun <R> executeBlockWith(isExecuteOnThreadOrUiThread: Boolean, block: () -> R): Job? {
val isAlreadyOnMainThread = Looper.getMainLooper() == Looper.myLooper()
var executeJob: Job? = null
if (isExecuteOnThreadOrUiThread) {//需要在工作线程中执行
if (isAlreadyOnMainThread) {
executeJob = CoroutineScope(Dispatchers.Default).launch {
block()
}
} else {
block()
}
} else {//需要在UI线程中执行
if (isAlreadyOnMainThread) {
block()
} else {
executeJob = MainScope().launch {
block()
}
}
}
return executeJob
}
fun <R> executeBlockOnWorkThread(executeDelayTimeMills: Long = 0, block: () -> R): Job? {
return CoroutineScope(Dispatchers.Default).launch{
if (executeDelayTimeMills > 0) {
delay(executeDelayTimeMills)
}
block()
}
}