当前位置:网站首页>Android kotlin uses a coroutine instead of a callback function (suspendcoroutine usage)
Android kotlin uses a coroutine instead of a callback function (suspendcoroutine usage)
2022-07-24 07:58:00 【catzifeng】
List of articles
One 、 sketch
If we say that everyone is already familiar with the process , But hold a handful of unopened Peerless sword , But it can't exert its real power ! Or you are not very familiar with the process , It is not clear what the benefits of the cooperation process are ?
This article will bring you Tongqiao level Experience .
Two 、 Example
2.1 Common writing
To get a View Take the width and height of .
Usually we get one View The width and height of , It's all done :
view.post {
val height = view.measuredHeight
val width = view.measuredWidth
}
Because at least we need to wait View The layout process of , We can get View True width and height of .
Then how to replace this callback with a coroutine ? Please look at :
2.2 It's written in synergetic way
// 1. Create a View The extension function of await()
suspend fun View.await() = suspendCoroutine<View> {
coroutine->
this.post {
// 2. stay View.post Within the function , Return itself
coroutine.resume(this)
}
}
Use ( In order to let everyone see the effect , Just put the screenshot ):
A little explanation , launch() It's my own right GlobalScope.launch() Function after encapsulation , This can be seen as directly opening a collaboration scope . Then let view call await() function , The returned value is after the width and height are determined View La .
3、 ... and 、 Callback with success and failure
3.1 Common writing
Let's take the success or failure of obtaining a data as an example :
fun getData(onSuccess:(String)->Unit,onFail:(Throwable)->Unit){
Thread.sleep(1000)
if ((Math.random() *10).toInt() % 2 == 0){
onSuccess(" data ")
}else{
onFail(IllegalStateException(" Failed to get data "))
}
}
Use :
3.2 It's written in synergetic way
suspend fun getData() = suspendCoroutine<String> {
Thread.sleep(1000)
if ((Math.random() *10).toInt() % 2 == 0){
it.resume(" data ")
}else{
it.resumeWithException(IllegalStateException(" Failed to get data "))
}
}
Use :
GlobalScope.launch {
val data = getData()
// < If you can get the data , Then keep going down >
println("data:${
data}")
}
If getData() Can successfully return data , Then it's no problem to write like this , however If it fails , That will throw an exception , So we have to use try catch sentence :
GlobalScope.launch {
try {
val data = getData()
// < If you can get the data , Then keep going down >
println("data:${
data}")
}catch (e:Throwable){
// < Failed to get data and caught exception >
}
}
Compare the previous writing …… Do you think it's not as good as the previous writing ? So we can use the context of collaboration ——CoroutineConext Come and make trouble ……
3.3 Use the context of the collaboration to handle exceptions
- Let's first create a custom context class for handling exceptions :
abstract class NetErrorContext:AbstractCoroutineContextElement(NetErrorContext){
companion object Key: CoroutineContext.Key<NetErrorContext>
abstract fun handleException(throwable: Throwable)
}
This is a very typical and template writing ……
It doesn't matter if you don't understand , Write down this template , If you are free in the future, write an article about the context of collaboration .
- Then we let the context handle exceptions :
suspend fun getData() = suspendCoroutine<String> {
Thread.sleep(1000)
if ((Math.random() *10).toInt() % 2 == 0){
it.resume(" data ")
}else{
//it.resumeWithException(IllegalStateException(" Failed to get data "))
it.context[NetErrorContext]?.handleException(IllegalStateException(" Failed to get data "))
}
}
- Define an exception handling object :
val netErrorHandler = object :NetErrorContext(){
override fun handleException(throwable: Throwable) {
println(" Network request exception ……")
}
}
- Finally, when starting the synergetic body , Add context :
GlobalScope.launch(context = netErrorHandler) {
val data = getData()
// < If you can get the data , Then keep going down >
println("data:${
data}")
}
In this case , If there is an exception, it will be netErrorHandler Capture to . And back to this plain writing ……
Of course , When you customize the context yourself , You can implement some methods according to your business , The above example only defines a handleException() Method , And only one parameter is defined , In the actual development process , This is still very flexible …… And the context of the process can be superimposed ……
边栏推荐
- Use JMeter to analyze and test the lottery probability of the lottery interface
- JMeter stress test index interpretation
- Why is knowledge base important? This is the best answer I've ever heard
- Debug No3 multi texture overlay
- Intelligent robots and intelligent systems (Professor Zhengzheng of Dalian University of Technology) -- 3. Industrial robots
- 学习笔记总结篇(一)
- [target detection] IOU (intersection and combination ratio)
- 2021-06-03pip error valueerror: unable to find resource t64.exe in package pip_ vendor.distlib
- The vision group of Hegong University Sky team trained day3 - machine learning, strengthened the use of Yolo models, and learned pumpkin books and watermelon books
- Markdown basic grammar learning
猜你喜欢

NFT是什么?一篇文章搞懂NFT的概念

hcip第八天笔记

Debug No3 multi texture overlay

【MATLAB】(四)MATLAB在线性代数中的应用

Robot operation continuous learning thesis (1) original text reading and Translation -- primitive generation strategy learning without catastrophic forgetting in robot operation

Vertex buffer and shader (the cherno + leranopongl) notes

Digital twin demonstration project -- Talking about simple pendulum (3) solid model exploration

Movie recommendation system

Do you want to have a robot that can make cartoon avatars in three steps?

Why is knowledge base important? This is the best answer I've ever heard
随机推荐
2022-07-23: given n items, each item has weight (w[i]) and value (v[i]), only two items can be selected at most, and the weight does not exceed bag. What is the maximum return value? N <= 10^5, w[i] <
Selenium basic knowledge automatically login Baidu Post Bar
[target detection] IOU (intersection and combination ratio)
2021-06-03 database query - sorting
Implement a queue with two stacks.
*Code understanding *numpy basic (plus code) that must be understood
Automatic test and manual test
MySQL 啥时候用表锁,啥时候用行锁?
HCIP第十天笔记
Learning to track at 100 FPS with deep progression networks
Hcip day 8 notes
What is the NFT concept.. Fully understand NFT market, technology and cases
Binary search common questions
Intelligent robots and intelligent systems (Professor Zheng Zheng of Dalian University of Technology) -- 2. Mobile Robot Perception
*Yolo5 learning * data experiment based on yolo5 face combined with attention model se
Anaconda cannot shut down the method of forced shutdown
hcip第十三天笔记
Collection of linked list topics
55. Jumping game
Why is knowledge base important? This is the best answer I've ever heard