1. 协程的定义
2.协程的使用
fun showPopView(context:Activity){
context.window?.decorView?.let {
GlobalScope.launch{
val result= try {
getUser()
}catch (e:Exception){
null
}?:return
if (result.isVip){
context.window?.decorView?.let {
Handler(Looper.getMainLooper()).postDelayed({ showNoVipIncome(context, it) }, 500L)
}
}
withContext(Dispatchers.Main) {
context.window?.decorView?.apply {
showVipIncome(context, this, force)
}
}
}
}
}
suspend fun getUser(){
}
fun showNoVipIncome(context:Activity,view:View){
}
Flow 的使用:
Flow 的创建三种方式:
flowOf(1,2,3,4,5)
listOf(1, 2, 3, 4, 5).asFlow()
flow{ ... }构建
channelFlow{...}
fun foo():Flow<Int> = flow{
for (i in 1..3){
delay(100)
emit(i)
}
}
suspend fun main(){
foo().collect {
println(it)
}
}
flow{ ... }构建一个Flow类型
flow { ... }内可以使用suspend函数.
foo()不需要是suspend函数
emit方法用来发射数据
collect方法用来遍历结果 不会阻塞UI主线程
Flows像Sequences一样是冷流,即在调用collect之前,flow{ ... }中的代码不会执行