Android LiveData 替代 EventBus

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(...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章