for (i in 0..10) { println("Asynchronous request executing: getToken :$i") delay(100) } return "ask"
}
suspend fun getResponse(token: String): String {
for (i in 0...10) {
println("asynchronous request executing: getresponse: $token $I")
delay(100)
}
return "response"
}
fun setText(response: String) {
println("setText executed on ${System.currentTimeMillis()}")
}
fun main() {
GlobalScope.launch(Dispatchers.Unconfined) {
var token = GlobalScope.async(Dispatchers.Unconfined) {
return@async getToken()
}. await() / / creates an asynchronous task, and blocking execution of await is the result of blocking execution
var response = GlobalScope.async(Dispatchers.Unconfined) { return@async getResponse(token) }.await() // Create an asynchronous task and execute it immediately setText(response) } Thread.sleep(20000)
}
Execution results: ```kotlin Asynchronous request executing: getToken :0 Asynchronous request executing: getToken :1 Asynchronous request executing: getToken :2 Asynchronous request executing: getToken :3 Asynchronous request executing: getToken :4 Asynchronous request executing: getToken :5 Asynchronous request executing: getToken :6 Asynchronous request executing: getToken :7 Asynchronous request executing: getToken :8 Asynchronous request executing: getToken :9 Asynchronous request executing: getToken :10 Asynchronous request executing: getResponse :ask 0 Asynchronous request executing: getResponse :ask 1 Asynchronous request executing: getResponse :ask 2 Asynchronous request executing: getResponse :ask 3 Asynchronous request executing: getResponse :ask 4 Asynchronous request executing: getResponse :ask 5 Asynchronous request executing: getResponse :ask 6 Asynchronous request executing: getResponse :ask 7 Asynchronous request executing: getResponse :ask 8 Asynchronous request executing: getResponse :ask 9 Asynchronous request executing: getResponse :ask 10 setText Execution, time: 1578904290520
-
An asynchronous task is currently being executed, but you suddenly don't want it to be executed. You can cancel it at any time
fun main() { // Collaborative task val job = GlobalScope.launch(Dispatchers.IO) { for (i in 0..100){// Suspend 100MS every time, which is 10 seconds println("The coordination process is being implemented $i") delay(100) } } // But I cancelled the process in one second Thread.sleep(1000) job?.cancel() println( "btn_right End the process") }
Execution results (100 rounds of printing should have been executed, and only 10 rounds lasted):
Collaboration is executing 0 Collaboration in progress 1 The collaboration is being executed 2 The collaboration is in progress 3 The collaboration is being implemented 4 The cooperation process is being implemented 5 The collaboration is being implemented 6 The collaboration is being implemented 7 The collaboration is being implemented 8 The collaboration is being implemented 9 btn_right End the process Process finished with exit code 0
-
If you want a task to be executed for 3 seconds at most, it will be automatically cancelled if it exceeds 3 seconds
import kotlinx.coroutines.* fun main() = runBlocking { println("The results of time limited tasks are:" + getResFromTimeoutTask()) } suspend fun getResFromTimeoutTask(): String? { // Forget, it will ensure that the internal collaboration code is executed, so it can't be written like this return withTimeoutOrNull(1300) { for (i in 0..10) { println("I'm sleeping $i ...") delay(500) } "end of execution" } }
results of enforcement
I'm sleeping 0 ... I'm sleeping 1 ... I'm sleeping 2 ... The results of time limited tasks are: null Process finished with exit code 0
summary
As a new concept of kotlin different from java, coprocessing is to solve the problems that java can not solve, such as code bloated caused by layers of callback, such as poor control of asynchronous task execution process, etc. This chapter is limited in length and cannot be explained, but for novices, after reading this chapter, they should be able to have a general understanding of the role of collaborative process. I am also a preliminary study. After I have a deeper understanding, I will explain it in a special article.
operators overloading
concept
Human words, such as unary operator + + self addition and binary operator + addition, only support numeric types by default, such as Int. however, through operator overloading, we can make any class + + self addition and return a desired object. The logic implemented by the operator depends entirely on how we design it.
classification
By element level
-
one yuan
expression Corresponding function +a a.unaryPlus() -a a.unaryMinus() !a a.not() a++ a.inc() a– a.dec() -
binary
expression Corresponding function a+b a.plus(b) a-b a.minus(b) a*b a.times(b) a/b a.div(b) a%b a.rem(b) a...b a.range(b) a in b b.contains(a) a !in b !b.contains(a) a[i] a.get(i) a[i,j] a.get(i,j) a[i_1,...,i_n] a.get(i_1,...,i_n) a[i]=b a.set(i,b) a[i,j]=b a.set(i,j,b) a[i_1,...,i_n]=b a.set(i_1,...,i_j,b) a() a.invoke() a(i) a.invoke(i) a(i,j) a.invoke(i,j) a(i_1,...,i_n) a.invoke(i_1,...,i_n) a+=b a.plusAssign(b) a-=b a.minusAssign(b) a*=b a.timesAssign(b) a/=b a.divAssign(b) a%=b a.modAssign(b) a > b a.compareTo(b)>0 a < b a.compareTo(b)<0 a>=b a.compareTo(b)>=0 a<=b a.compareTo(b)<=0
By implementation
-
Member function
-
spread function
Chestnuts
It must be a little confused to see a lot of above. Let's take an example to solve the problem. I have classified operator overloading in two dimensions above. First, try to overload a unary operator in the way of member function
class A(i: Int, j: Int) { var i: Int = i var j: Int = j /** * Overload + + operation */ operator fun inc(): A { return A(i++, j++) } override fun toString(): String { return "[i=$i , j=$j]" } }
See the code above:
operator fun inc(): A { return A(i++, j++) }
Kotlin's operator overloading is completely different from that in c + +, dart language. It no longer directly puts operators in the process of rewriting, but each operator that supports overloading has a corresponding function name
Just like the a + + operator in the above table, the corresponding function is a.inc()
When calling:
fun main() { var a = A(1, 2) println("a:$a") println("a++:${a++}") }
Print results:
a:[i=1 , j=2] a++:[i=2 , j=3]
Let's look at a chestnut overloaded with binary operators. This time, instead of member functions, we use extension functions:
class A(i: Int, j: Int) { var i: Int = i var j: Int = j override fun toString(): String { return "[i=$i , j=$j]" } } /** * Overloaded class A x+y operation */ operator fun A.plus(a: A): A { return A(this.i + a.i, this.j + a.j) } fun main() { val x = A(1,1) val y = A(2,2) println(x+y) }
Here is A class A x+y operator overload. There should be no more details.
Print results:
[i=3 , j=3]
Another complex chestnut, overload a[i]
/** * For example, there is a member in class B, list. I want to overload the operator and directly get the elements in the list */ class B { val list: MutableList<Int> = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9) } //a[i] operator fun B.get(i: Int): Int { return list[i] } fun main() { val b = B() println("${b[2]}") }
Print results:
3
The last Chestnut: a > b, the corresponding function is: a.compare(b)
/** * Student class */ data class Student(val math: Int = 0, val chinese: Int = 0, val english: Int = 0) fun Student.toString():String{ return "[math:${math} chinese:${chinese} english:${english}]" } fun Student.totalScore(): Int { return math + chinese + english } /** * For example, we should directly compare the total scores of two students */ operator fun Student.compareTo(s: Student): Int { return this.totalScore() - s.totalScore()//Compare the total scores of two students } fun main() { val s1 = Student(math = 50, chinese = 90, english = 100) val s2 = Student(math = 80, chinese = 70, english = 60) println("s1:${s1}") println("s2:${s2}") //For example, there are two students. I want to know whose total score is higher and whose is lower println("student s1,s2 Total score of:${if(s1 > s2) "s1 Relatively high" else "s2 Relatively high" }")