最后
有任何问题,欢迎广大网友一起来交流,分享高阶Android学习视频资料和面试资料包~
偷偷说一句:群里高手如云,欢迎大家加群和大佬们一起交流讨论啊!
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
delay(3000)
println(“bbb”)
}
println(“222”)
defaultMode.join()
}
suspend fun testLazyMode() {
val defaultMode = GlobalScope.async(start = CoroutineStart.LAZY) {
println(“aaa”)
delay(3000)
println(“bbb”)
}
println(“222”)
defaultMode.await()
}
@ExperimentalCoroutinesApi
suspend fun testUNDISPATCHEDMode() {
val defaultMode = GlobalScope.launch(start = CoroutineStart.UNDISPATCHED) {
println(“aaa”)
delay(3000)
println(“bbb”)
}
println(“222”)
defaultMode.join()
}
Default和IO线程的区别,IO内部多了一个队列的维护
回调转协程的完整写法:
import com.bennyhuo.kotlin.coroutines.advanced.common.gitHubServiceApi
import kotlinx.coroutines.suspendCancellableCoroutine
import retrofit2.Call
import retrofit2.Callback
import retrofit2.HttpException
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
suspend fun Call.await(): T = suspendCancellableCoroutine { //可取消
continuation ->
continuation.invokeOnCancellation {
cancel() //调用retrofit的取消方法
}
enqueue(object: Callback {
override fun onFailure(call: Call, t: Throwable) {
continuation.resumeWithException(t)
}
override fun onResponse(call: Call, response: Response) {
response.takeIf { it.isSuccessful }?.body()?.also {continuation.resume(it) }
?: continuation.resumeWithException(HttpException(response))
}
})
}
suspend fun main() {
val user = gitHubServiceApi.getUserCallback(“flycumt”).await()
println(user)
}
也可以不自己写,retrofit的api中本身有实现await()
方法,awaitResponse()
方法等。
CompletableFuture 添加回调的写法:
import com.bennyhuo.kotlin.coroutines.advanced.utils.log
import kotlinx.coroutines.suspendCancellableCoroutine
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
suspend fun main() {
val result = CompletableFuture.supplyAsync {
3
}.await()
log(result)
}
suspend fun CompletableFuture.await(): T {
if(isDone){
try {
return get()
} catch (e: ExecutionException) {
throw e.cause ?: e
}
}
return suspendCancellableCoroutine { //可取消
cancellableContinuation ->
cancellableContinuation.invokeOnCancellation {
cancel(true) //取消
}
whenComplete { value, throwable ->
if(throwable == null){
cancellableContinuation.resume(value)
} else {
cancellableContinuation.resumeWithException(throwable.cause ?: throwable)
}
}
}
}
CompletableFuture本身也有实现await()
方法。
模仿给Handler扩展添加可取消的支持:
suspend fun Handler.run(block: () -> T) = suspendCoroutine { continuation ->
post {
try {
continuation.resume(block())
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
}
suspend fun Handler.runDelay(delay: Long, block: () -> T) = suspendCancellableCoroutine { continuation ->
val message = Message.obtain(this) { //Message obtain(Handler h, Runnable callback)
try {
continuation.resume(block())
} catch (e: Exception){
continuation.resumeWithException(e)
}
}.also {
it.obj = continuation //message.obj
}
continuation.invokeOnCancellation {
removeCallbacksAndMessages(continuation) //通过Handler的removeCallbacksAndMessages方法来取消回调, 参数就是前面设置的message.obj的值
}
sendMessageDelayed(message, delay)
}
suspend fun main() {
Looper.prepareMainLooper()
GlobalScope.launch {
val handler = Handler(Looper.getMainLooper())
val result = handler.run { “Hello” }
val delayedResult = handler.runDelay(5000){ “World” }
log(result, delayedResult)
Looper.getMainLooper().quit()
}
Looper.loop()
}
这个例子的主要意图是,Hanlder可以通过定义扩展函数的方式来延时获取一些东西,比如Activity刚创建的时候,拿不到view的宽和高,就可以使用这种方法。
上面三个例子主要是针对可取消的写法,如果实际用,不用自己写,直接导库就行。
其中CONFLATED比较适合用于状态更新,比如进度条的进度,因为它总是只取最新的。
关闭后再发送会抛异常:
channel关闭后,channel中的数据仍然可以被接受,只有当channel中的数据消费完了,isClosedForReceive才为true.
suspend fun main() {
basics()
}
suspend fun basics() {
val channel = Channel(Channel.RENDEZVOUS)
// val channel = Channel(Channel.UNLIMITED)
// val channel = Channel(Channel.CONFLATED)
// val channel = Channel(Channel.BUFFERED)
// val channel = Channel(1)
//生产者 发
val producer = GlobalScope.launch {
for (i in 0…3) {
log(“sending”, i)
channel.send(i)
log(“sent”, i)
}
channel.close()
}
//消费者 收
val consumer = GlobalScope.launch {
while (!channel.isClosedForReceive) {
log(“receiving”)
val value = channel.receiveOrNull()
log(“received”, value)
}
}
producer.join()
consumer.join()
}
Channel(Channel.RENDEZVOUS ) 的方式是发一个收一个,边发边收,如果没有接受的,发送者会挂起等待,输出如下:
Channel(Channel.UNLIMITED ) 的方式是全部发送完毕,才会接收到,先发后收,发送者发送完就返回了,不管有没有接受者,输出如下:
Channel(Channel.CONFLATED ) 的方式是不管发了多少个,只能收到最后一个,也是发送完就返回了,不管有没有接受者,输出如下:
Channel(Channel.BUFFERED ) 的方式也是发送者发送完就返回了,不管有没有接受者,可以指定buffer大小,输出如下:
Channel(1) 的方式指定管道的容量大小,如果数据超过容量,发送者就会挂起等待,直到有接受者取走数据,发送者才发送下一批数据,
channel接受数据的时候可以直接当成迭代器使用:
suspend fun iterateChannel() {
val channel = Channel(Channel.UNLIMITED)
val producer = GlobalScope.launch {
for (i in 0…3) {
log(“sending”, i)
channel.send(i)
log(“sent”, i)
}
channel.close()
}
val consumer = GlobalScope.launch {
for (i in channel) {
log("received: ", i)
}
}
producer.join()
consumer.join()
}
suspend fun producer() {
val receiveChannel = GlobalScope.produce(capacity = Channel.UNLIMITED) {
for (i in 0…3) {
log(“sending”, i)
send(i)
log(“sent”, i)
}
}
val consumer = GlobalScope.launch {
for (i in receiveChannel) {
log("received: ", i)
}
}
consumer.join()
}
suspend fun consumer() {
val sendChannel = GlobalScope.actor(capacity = Channel.UNLIMITED) {
for (i in this) {
log("received: ", i)
}
}
val producer = GlobalScope.launch {
for (i in 0…3) {
log(“sending”, i)
sendChannel.send(i)
log(“sent”, i)
}
}
producer.join()
}
suspend fun broadcast() {
//下面几种都可以创建一个BroadcastChannel
//val broadcastChannel = BroadcastChannel(Channel.BUFFERED)
//val broadcastChannel = Channel(Channel.BUFFERED).broadcast()
val broadcastChannel = GlobalScope.broadcast {
for (i in 0…5) {
send(i)
}
}
//启动5个接受者,每个都能收到
List(5) { index ->
GlobalScope.launch {
val receiveChannel = broadcastChannel.openSubscription()
for (i in receiveChannel) {
log(“[#$index] received: $i”)
}
}
}.joinAll()
}
输出:
Task :ChannelsKt.main()
21:07:12:924 [DefaultDispatcher-worker-3 @coroutine#2] [#0] received: 0
21:07:12:924 [DefaultDispatcher-worker-5 @coroutine#6] [#4] received: 0
21:07:12:924 [DefaultDispatcher-worker-1 @coroutine#3] [#1] received: 0
21:07:12:925 [DefaultDispatcher-worker-4 @coroutine#5] [#3] received: 0
21:07:12:925 [DefaultDispatcher-worker-2 @coroutine#4] [#2] received: 0
21:07:12:944 [DefaultDispatcher-worker-1 @coroutine#3] [#1] received: 1
21:07:12:943 [DefaultDispatcher-worker-3 @coroutine#2] [#0] received: 1
21:07:12:943 [DefaultDispatcher-worker-5 @coroutine#6] [#4] received: 1
21:07:12:944 [DefaultDispatcher-worker-4 @coroutine#5] [#3] received: 1
21:07:12:945 [DefaultDispatcher-worker-2 @coroutine#4] [#2] received: 1
21:07:12:945 [DefaultDispatcher-worker-2 @coroutine#4] [#2] received: 2
21:07:12:945 [DefaultDispatcher-worker-8 @coroutine#3] [#1] received: 2
21:07:12:945 [DefaultDispatcher-worker-8 @coroutine#3] [#1] received: 3
21:07:12:945 [DefaultDispatcher-worker-7 @coroutine#4] [#2] received: 3
21:07:12:945 [DefaultDispatcher-worker-2 @coroutine#6] [#4] received: 2
21:07:12:946 [DefaultDispatcher-worker-2 @coroutine#6] [#4] received: 3
21:07:12:946 [DefaultDispatcher-worker-8 @coroutine#5] [#3] received: 2
21:07:12:946 [DefaultDispatcher-worker-8 @coroutine#5] [#3] received: 3
21:07:12:946 [DefaultDispatcher-worker-3 @coroutine#2] [#0] received: 2
21:07:12:946 [DefaultDispatcher-worker-3 @coroutine#2] [#0] received: 3
21:07:12:946 [DefaultDispatcher-worker-1 @coroutine#3] [#1] received: 4
21:07:12:946 [DefaultDispatcher-worker-3 @coroutine#2] [#0] received: 4
21:07:12:946 [DefaultDispatcher-worker-1 @coroutine#6] [#4] received: 4
21:07:12:947 [DefaultDispatcher-worker-6 @coroutine#5] [#3] received: 4
21:07:12:947 [DefaultDispatcher-worker-6 @coroutine#5] [#3] received: 5
21:07:12:947 [DefaultDispatcher-worker-2 @coroutine#3] [#1] received: 5
21:07:12:947 [DefaultDispatcher-worker-6 @coroutine#2] [#0] received: 5
21:07:12:947 [DefaultDispatcher-worker-2 @coroutine#6] [#4] received: 5
21:07:12:947 [DefaultDispatcher-worker-3 @coroutine#4] [#2] received: 4
21:07:12:947 [DefaultDispatcher-worker-3 @coroutine#4] [#2] received: 5
Select的使用场景是多个协程异步执行时,获取最先结束的那个协程结果返回,比如加载图片时,可能从网络获取,也可能从本地获取,这两种可能同时异步执行,使用Select就会优先获取返回比较快的本地结果展示,然后我们再去获取网络最新的更新即可。
使用例子:
val localDir = File(“localCache”).also { it.mkdirs() }
val gson = Gson()
fun CoroutineScope.getUserFromApi(login: String) = async(Dispatchers.IO){
gitHubServiceApi.getUserSuspend(login)
}
fun CoroutineScope.getUserFromLocal(login:String) = async(Dispatchers.IO){
File(localDir, login).takeIf { it.exists() }?.readText()?.let { gson.fromJson(it, User::class.java) }
}
fun cacheUser(login: String, user: User){
File(localDir, login).writeText(gson.toJson(user))
}
data class Response(val value: T, val isLocal: Boolean)
suspend fun main() {
val login = “test”
GlobalScope.launch {
val localDeferred = getUserFromLocal(login)
val remoteDeferred = getUserFromApi(login)
//val userResponse = Response(localDeferred.await(), true)
最后
最后这里放上我这段时间复习的资料,这个资料也是偶然一位朋友分享给我的,里面包含了腾讯、字节跳动、阿里、百度2019-2021面试真题解析,并且把每个技术点整理成了视频和PDF(知识脉络 + 诸多细节)。
还有 高级架构技术进阶脑图、高级进阶架构资料 帮助大家学习提升进阶,也可以分享给身边好友一起学习。
一起互勉~
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
data class Response(val value: T, val isLocal: Boolean)
suspend fun main() {
val login = “test”
GlobalScope.launch {
val localDeferred = getUserFromLocal(login)
val remoteDeferred = getUserFromApi(login)
//val userResponse = Response(localDeferred.await(), true)
最后
最后这里放上我这段时间复习的资料,这个资料也是偶然一位朋友分享给我的,里面包含了腾讯、字节跳动、阿里、百度2019-2021面试真题解析,并且把每个技术点整理成了视频和PDF(知识脉络 + 诸多细节)。
还有 高级架构技术进阶脑图、高级进阶架构资料 帮助大家学习提升进阶,也可以分享给身边好友一起学习。
[外链图片转存中…(img-RfH7SMwT-1715048563024)]
[外链图片转存中…(img-uuWDty9G-1715048563024)]
一起互勉~
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!