EventLiveData.kt
import androidx.lifecycle.LiveData
/**
* @author Afra55
* @date 2020/4/9
* A smile is the best business card.
*/
object EventLiveData :LiveData<EventMessage?>(){
fun sendEvent(type: Int, vararg any: Any) {
val dataList = arrayListOf<Any>()
for (v in any) {
dataList.add(v)
}
value = EventMessage(type, dataList)
emptyValue()
}
fun stickEvent(type: Int, vararg any: Any) {
val dataList = arrayListOf<Any>()
for (v in any) {
dataList.add(v)
}
value = EventMessage(type, dataList)
}
fun emptyValue() {
value = null
}
fun sendError(type: Int, errorCode: Int, errorMessage: String, errorObject: Any? = null) {
value = EventMessage(
type,
arrayListOf(
EventError(
errorCode,
errorMessage,
errorObject
)
)
)
emptyValue()
}
}
/**
* @author Afra55
* @date 2019-06-20
* A smile is the best business card.
*/
class EventMessage(var type:Int, var listAny:ArrayList<Any>? ){
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): EventMessage? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
this
}
}
fun getDefaultObj(): Any? {
if (listAny == null || listAny!!.isEmpty()) {
return null
}
return listAny!![0]
}
override fun toString(): String {
return "EventMessage(type=$type, listAny=$listAny)"
}
}
data class EventError(val errCode:Int, val errMsg:String, var errorObj:Any? = null)
监听
EventLiveData.observe(this,
Observer {
})
发送
EventLiveData.sendEvent(...)
EventLiveData.sendError(...)