# 讓api再打一次
###### tags: `簡報`
can use in 樂觀鎖
---
## lambda
```kotlin=
val lambdaVariable: () -> Unit = {
}
val anotherOne: (Int) -> String - {
it.toString()
}
```
---
## higherOrder Function
```kotlin=
fun high(l:() -> Unit){
l.invoke()
}
fun main(){
val lambdaVariable: () -> Unit = {
//do something
}
high(lambdaVariable)
//or
high {
}
}
```
---
## suspend
```kotlin=
fun normalBlockingFunction(){
//blocking code
}
// add withContext and suspend
// not blocking main thread
suspend fun normalBlockingFunction(){
withContext(Dispatcher.IO){
//blocking code
}
}
```
---
## extension function
```kotlin=
fun Int.times(i:Int):Int{
return this * i
}
fun main(){
println(100.times(5))//500
}
```
---
## suspend lambda to higherOrder function
```kotlin=
suspend fun <T> retryWithTimes(times:Int = 3, block: suspend () -> T) : T {
var actuallyTimes = 1
var error:Exception? = null
if (times < 1) throw Exception("retry times shouldn't less than one")
while (actuallyTimes <= times){
try {
println(actuallyTimes)
return block()
} catch (e:Exception) {
e.printStackTrace()
error = e
} finally {
actuallyTimes++
}
}
throw error ?: Exception("Unknown Exception")
}
```
---
## suspend extension lambda to higherOrder function
```kotlin=
suspend fun <T> CoroutineScope.retryWithTimes(
times:Int = 3, block: suspend CoroutineScope.() -> T
) : T {
var actuallyTimes = 1
var error:Exception? = null
if (times < 1) throw Exception("retry times shouldn't less than one")
while (actuallyTimes <= times){
try {
println(actuallyTimes)
return block(this)
} catch (e:Exception) {
e.printStackTrace()
error = e
} finally {
actuallyTimes++
}
}
throw error ?: Exception("Unknown Exception")
}
```
---
## retry with times
```kotlin=
CoroutineScope(Job()).launch{
try {
retryWithTimes{
getList()
}
} catch(e:exception){
//show error ui
}
try {
retryWithTimes (times = 5){
getList()
}
} catch(e:exception){
//show error ui
}
}
```
---
## retry in 60 seconds
```kotlin=
suspend fun <T> retryIo(block : suspend () -> T):T {
var curDelay = 1000L
while (true){
try {
return block()
} catch (e:IOException){
e.printStackTrace()
}
delay(curDelay)
curDelay = (curDelay * 2).coerceAtMost(60000L)
}
}
```
---
{"metaMigratedAt":"2023-06-16T19:22:03.109Z","metaMigratedFrom":"Content","title":"讓api再打一次","breaks":"true","contributors":"[{\"id\":\"b07ca9a3-1ebc-4263-a0c7-51e30de31ed0\",\"add\":4084,\"del\":1295}]"}