18034727885
2026-04-14 370014cbb9ec1ef64e7e42bb4f9a12671461d8e4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package com.xw.common.base
 
import android.app.Application
import android.os.Bundle
import com.xw.common.utils.LogUtils
import android.view.View
import androidx.lifecycle.*
import com.blankj.utilcode.util.AppUtils
import com.xw.common.utils.MMKVManager
import com.xw.common.net.interceptor.ApiException
import com.xw.common.utils.ToastUtilCommon
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import java.io.IOException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.*
 
open class BaseViewModel(application: Application) : AndroidViewModel(application),
    IBaseViewModel, KoinComponent {
 
    var TAG = "zmc-${this.javaClass.simpleName}"
 
    /**
     * 协程全局异常处理器,防止未捕获异常导致崩溃
     */
    private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
        LogUtils.e(TAG, "Uncaught coroutine exception: ${throwable.message}")
        runOnMainThread {
            ToastUtilCommon.showError(getNetworkErrorMessage(throwable))
        }
    }
 
    var startActivityEvent: SingleLiveEvent<MutableMap<String, Any?>> = SingleLiveEvent()
    var onBackEvent: SingleLiveEvent<String> = SingleLiveEvent()
    var closeEvent: SingleLiveEvent<String> = SingleLiveEvent()
    var dialogEvent: SingleLiveEvent<String> = SingleLiveEvent()
 
    fun finish() {
        onBackEvent.postValue("finish")
    }
 
    fun onBackPressed() {
        onBackEvent.postValue("back")
    }
 
    // 当前正在显示的dialog数量
    var currentDialogNum = 0
    fun showDialog(content: String = "请稍后...") {
        currentDialogNum++
        dialogEvent.postValue(content)
    }
 
    fun dismissDialog() {
        if (currentDialogNum > 0) currentDialogNum--
        if (currentDialogNum == 0) {
            dialogEvent.postValue("dismiss")
        }
    }
 
    fun forceDismissDialog() {
        LogUtils.e(TAG, "forceDismissDialog: $currentDialogNum")
        currentDialogNum = 0
        dialogEvent.postValue("dismiss")
    }
 
    fun launchRequest(
        tips: String = "加载中...",
        showLoading: Boolean = true,
        error: suspend (code: Int, msg: String) -> Unit = { code, msg ->
            ToastUtilCommon.showError(msg)
            LogUtils.e(TAG, "launchRequest: code = $code msg = $msg", )
        },
        request: suspend () -> Unit
    ) {
        if (showLoading) showDialog(tips)
        viewModelScope.launch(Dispatchers.IO + exceptionHandler) {
            try {
                request()
            } catch (e: Throwable) {
                try {
                    errorHandling(e, error)
                } catch (handlingError: Throwable) {
                    LogUtils.e(TAG, "Error handling failed: ${handlingError.message}")
                }
            } finally {
                if (showLoading) dismissDialog()
            }
        }
    }
 
 
    fun <T> launchRequestFlow(
        tips: String = "加载中...",
        showLoading: Boolean = true,
        error: suspend (code: Int, msg: String) -> Unit = { code, msg ->
            ToastUtilCommon.showError(msg)
            LogUtils.e(TAG, "launchRequestFlow: code = $code msg = $msg")
        },
        flowBlock: () -> Flow<T>,
        onCollect: (T) -> Unit
    ) {
        if (showLoading) showDialog(tips)
        viewModelScope.launch(Dispatchers.IO + exceptionHandler) {
            try {
                flowBlock().collect { data ->
                    onCollect(data)
                }
            } catch (e: Throwable) {
                try {
                    errorHandling(e, error)
                } catch (handlingError: Throwable) {
                    LogUtils.e(TAG, "Error handling failed: ${handlingError.message}")
                }
            } finally {
                if (showLoading) dismissDialog()
            }
        }
    }
 
    private suspend fun errorHandling(e: Throwable, error: suspend (code: Int, msg: String) -> Unit) {
        if (e is ApiException) {
            when {
                e.isTokenExpired() -> {
                    MMKVManager.getInstance().clear()
                    ToastUtilCommon.showWarn("登录已过期,请重新登录")
                    viewModelScope.launch {
                        delay(1000)
                        AppUtils.relaunchApp(true)
                    }
                }
 
                else -> {
                    error.invoke(e.code, e.message ?: "")
                }
            }
        } else {
            val errorMsg = getNetworkErrorMessage(e)
            error.invoke(-1, errorMsg)
        }
    }
 
    /**
     * 获取网络异常的友好提示信息
     */
    private fun getNetworkErrorMessage(e: Throwable): String {
        return when (e) {
            is UnknownHostException -> "网络连接失败,请检查网络设置"
            is ConnectException -> "无法连接到服务器,请检查网络"
            is SocketTimeoutException -> "连接超时,请稍后重试"
            is SocketException -> "网络异常,请检查网络连接"
            is IOException -> "网络请求失败,请检查网络"
            else -> e.message ?: "未知错误"
        }
    }
 
    fun runOnMainThread(block: () -> Unit) {
        viewModelScope.launch(Dispatchers.Main) {
            block()
        }
    }
 
    fun onBack(view: View) {
        onBackPressed()
    }
 
    /**
     * 需要登录的跳转页面
     *
     * @param clz 所跳转的目的Activity类
     */
    open fun startActivityNeedLoad(clz: Class<*>?) {
        startActivity(clz, null)
    }
 
    /**
     * 跳转页面
     *
     * @param clz 所跳转的目的Activity类
     */
    open fun startActivity(clz: Class<*>?) {
        startActivity(clz, null)
    }
 
    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    open fun startActivity(clz: Class<*>?, bundle: Bundle?) {
        val params: MutableMap<String, Any?> = HashMap()
        params["CLASS"] = clz
        if (bundle != null) {
            params["BUNDLE"] = bundle
        }
        startActivityEvent.postValue(params)
    }
 
    fun startActivityForResult(clz: Class<*>?, code: Int, bundle: Bundle? = null) {
        val params: MutableMap<String, Any?> = HashMap()
        params["CLASS"] = clz
        params["requestCode"] = code
        if (bundle != null) {
            params["BUNDLE"] = bundle
        }
        startActivityEvent.postValue(params)
    }
 
    fun closeKeyboard() {
        closeEvent.postValue("close")
    }
 
    fun hideKeyboard() {
        closeEvent.postValue("hide")
    }
 
    override fun onCreate() {}
 
    override fun onDestroy() {}
 
    override fun onStart() {}
 
    override fun onStop() {}
 
    override fun onResume() {}
 
    override fun onPause() {}
 
}