添加了界面及逻辑
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package com.sw.platecabinet.viewmodel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.sw.plate.utils.ToastUtils
|
||||
import com.sw.platecabinet.model.response.ApiResponse
|
||||
import com.sw.platecabinet.network.ApiClient
|
||||
import com.sw.platecabinet.repository.RemoteRepository
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
|
||||
abstract class BaseViewModel() : ViewModel() {
|
||||
protected val repository = RemoteRepository(ApiClient.apiService)
|
||||
|
||||
// 显示进度条
|
||||
private val _showLoading = MutableStateFlow<Boolean>(false)
|
||||
val showLoading: StateFlow<Boolean> = _showLoading
|
||||
|
||||
/**
|
||||
* 带进度条的请求
|
||||
*/
|
||||
protected fun launchWithLoading(block: suspend () -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_showLoading.value = true
|
||||
block()
|
||||
} catch (e: Exception) {
|
||||
// 错误处理可被子类重写
|
||||
handleError(e)
|
||||
} finally {
|
||||
_showLoading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 不带进度条的请求
|
||||
*/
|
||||
protected fun launch(block: suspend () -> Unit) {
|
||||
viewModelScope.launch() {
|
||||
try {
|
||||
block()
|
||||
} catch (e: Exception) {
|
||||
// 错误处理可被子类重写
|
||||
handleError(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected open fun parseResponse(response: ApiResponse<*>): Boolean {
|
||||
if (response.isSuccess()) {
|
||||
return true
|
||||
}
|
||||
Timber.d("msg = ${response.msg}, code = ${response.code}")
|
||||
ToastUtils.showToast("${response.msg}(${response.code})")
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
fun handleError(exception: Exception) {
|
||||
Timber.d("handleError ${exception.message}")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user