Kotlin中使用携程对回调进行简化

it2024-08-10  58

Kotlin中使用携程对回调进行简化

1 、首先看一下普通回调

fun main(){ val demo = Demo(object : CallBack{ override fun call(str: String) { print("call back data is :$str"); } }) //调用回调方法 demo.testCall() } object Demo { fun testCall(callBack: CallBack){ callBack.call("hello world !") } } //定义一个接口 interface CallBack{ fun call(str: String) }

运行结果如下:

2、下面使用携程对其进行简化操作:

首先介绍suspendCoroutine函数 此函数必须在协程作用域或挂起函数中才能使用,它接受一个Lambda表达式,主要作用是将当前协程挂起,然后再普通线程中执行Lambda中的代码,并且在表达式中会传入一个Continuation参数,只需调用resume()或resumeWithExceptionm()方法恢复协程运行

此函数介绍摘自《第一行代码第三版》

fun main(){ val str = testCall("http://www.baidu.com") println(str) } object Demo{ fun testCall(call: Call){ call.call("hello world !") } } //定义一个接口 interface Call{ fun call(str: String) } suspend fun testCall(url: String): String{ return suspendCoroutine { Demo.testCall(object : Call{ override fun call(str: String) { it.resume("hello world ! by suspendCoroutine $url") } }) } }

运行结果如下

由上代码可以看出使用携程进行回调操作十分简洁只需一行代码就可以获取到回调结果不需要使用匿名内部类的方式

将此方式用于网络请求的返回数据这样代码不仅简洁易读也降低了重复代码量

PS:在书上看到这样的方法对于之前使用Java的回调方式来说感觉十分奇妙所以就记录了下来如有不正确的地方望指出!

最新回复(0)