package com.xhly.corelib.base.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.xhly.corelib.network.bean.ResponseData
import com.xhly.corelib.utils.LogShow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

open class CommonBaseViewModel : ViewModel() {
    private val error by lazy { MutableLiveData<Exception>() }

    //记录自定义的一些信息，用于数据处理
    public val netMessage by lazy { MutableLiveData<String>() }
    //记录自定义的一些信息，用于数据处理
    public val responseData by lazy { MutableLiveData<ResponseData<Any>>() }
    //运行在UI线程的协程
    fun launchUI(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch {
        try {
            block()
        } catch (e: Exception) {
            error.value = e
            LogShow(e.toString())
        }
    }

    /**
     * 请求失败，出现异常
     */
    fun getError(): LiveData<Exception> {
        return error
    }
}