Skip to content

Commit 1096649

Browse files
committed
加入对协程取消异常的处理
1 parent a8540a5 commit 1096649

File tree

5 files changed

+29
-17
lines changed

5 files changed

+29
-17
lines changed
Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,45 @@
11
package com.fmt.github.base.viewmodel
22

33
import androidx.lifecycle.*
4-
import kotlinx.coroutines.CoroutineScope
5-
import kotlinx.coroutines.launch
4+
import kotlinx.coroutines.*
5+
6+
//类型别名
7+
typealias LaunchBlock = suspend CoroutineScope.() -> Unit
8+
9+
typealias EmitBlock<T> = suspend LiveDataScope<T>.() -> T
10+
11+
typealias Cancel = (e: Exception) -> Unit
612

713
open class BaseViewModel : ViewModel() {
814

915
val mStateLiveData = MutableLiveData<StateActionEvent>()//通用事件模型驱动(如:显示对话框、取消对话框、错误提示)
1016

11-
fun launch(block: suspend CoroutineScope.() -> Unit) {//使用协程封装统一的网络请求处理
17+
fun launch(cancel: Cancel? = null, block: LaunchBlock) {//使用协程封装统一的网络请求处理
1218
viewModelScope.launch {
1319
//ViewModel自带的viewModelScope.launch,会在页面销毁的时候自动取消请求,有效封装内存泄露
1420
try {
1521
mStateLiveData.value = LoadState
1622
block()
1723
mStateLiveData.value = SuccessState
1824
} catch (e: Exception) {
19-
mStateLiveData.value = ErrorState(e.message)
25+
when (e) {
26+
is CancellationException -> cancel?.invoke(e)
27+
else -> mStateLiveData.value = ErrorState(e.message)
28+
}
2029
}
2130
}
2231
}
2332

24-
fun <T> emit(block: suspend LiveDataScope<T>.() -> T): LiveData<T> = liveData {
33+
fun <T> emit(cancel: Cancel? = null, block: EmitBlock<T>): LiveData<T> = liveData {
2534
try {
2635
mStateLiveData.value = LoadState
2736
emit(block())
2837
mStateLiveData.value = SuccessState
2938
} catch (e: Exception) {
30-
mStateLiveData.value = ErrorState(e.message)
39+
when (e) {
40+
is CancellationException -> cancel?.invoke(e)
41+
else -> mStateLiveData.value = ErrorState(e.message)
42+
}
3143
}
3244
}
3345
}

app/src/main/java/com/fmt/github/ext/XPopupExt.kt

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ import kotlin.coroutines.resume
1111

1212
//回调转协程
1313
suspend fun showConfirmPopup(context: Context, title: String, message: String) =
14-
suspendCancellableCoroutine<Boolean> { continuation -> //Continuation(本质还是回调接口),kotlin编译器的黑魔法帮我们做了封装处理了
14+
suspendCancellableCoroutine<Boolean> { continuation ->
15+
//Continuation(本质还是回调接口),kotlin编译器的黑魔法帮我们做了封装处理了
1516
XPopup.Builder(context)
1617
.asConfirm(
1718
title,
@@ -23,7 +24,8 @@ suspend fun showConfirmPopup(context: Context, title: String, message: String) =
2324
false
2425
)
2526
.show().also { popupView ->
26-
continuation.invokeOnCancellation {//在协程取消时,隐藏对话框
27+
continuation.invokeOnCancellation {
28+
//在协程取消时,隐藏对话框
2729
popupView.dismiss()
2830
}
2931
}

app/src/main/java/com/fmt/github/home/work/DownLoadWork.kt

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,10 @@ class DownLoadWork(context: Context, params: WorkerParameters) : CoroutineWorker
7272
}.otherwise {
7373
try {
7474
initNotification()
75-
withContext(Dispatchers.IO) {
76-
//withContext进行线程切换
77-
val responseBody =
78-
DownloadService.download(inputData.getString(DOWN_LOAD_URL).toString())
79-
startDown(responseBody.byteStream(), responseBody.contentLength())
80-
Result.success()
81-
}
75+
val responseBody =
76+
DownloadService.download(inputData.getString(DOWN_LOAD_URL).toString())
77+
startDown(responseBody.byteStream(), responseBody.contentLength())
78+
Result.success()
8279
} catch (e: Exception) {
8380
mNotificationManager.cancel(NOTIFY_ID)
8481
withContext(Dispatchers.Main) {

app/src/main/java/com/fmt/github/user/activity/UserInfoActivity.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ class UserInfoActivity : BaseDataBindActivity<ActivityUserInfoBinding>() {
5555
supportFragmentManager, this,
5656
FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
5757
)
58+
mViewPager.offscreenPageLimit = 2
5859
mTabLayout.setupWithViewPager(mViewPager)
5960
}
6061
}

app/src/main/java/com/fmt/github/user/viewmodel/UserViewModel.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import com.fmt.github.user.repository.UserRepository
1111

1212
class UserViewModel(private val mUserRepository: UserRepository) : BaseViewModel() {
1313

14+
//提供给xml文件进行绑定
1415
val mUserInfoModel = MutableLiveData<UserInfoModel>()
1516

1617
fun createOrGetAuthorization(): LiveData<AuthorizationRespModel> = emit {
@@ -44,11 +45,10 @@ class UserViewModel(private val mUserRepository: UserRepository) : BaseViewModel
4445
mUserRepository.searchUsers(query, sort, order, page).items
4546
}
4647

47-
fun getUserInfo(user: String): LiveData<UserInfoModel> {
48+
fun getUserInfo(user: String){
4849
launch {
4950
mUserInfoModel.value = mUserRepository.getUserInfo(user)
5051
}
51-
return mUserInfoModel
5252
}
5353

5454
fun getUserPublicRepos(user: String, page: Int): LiveData<List<ReposItemModel>> = emit {

0 commit comments

Comments
 (0)