- You can simply use it similer to LiveData.
- You can safely use it on background thread, and it will call observer on main thread.
allprojects {
repositories {
//...
maven { url 'https://www.jitpack.io' }
}
}
dependencies {
implementation 'com.github.dqh147258:EventLiveData:1.0.+'
}
For example:
First, create a singleton object like EventPool to hold the EventLiveData.
object EventPool {
val userInfoUpdateEvent = EventLiveData<Boolean>(STICKY_FOREVER, false)
val userInfoShouldUpdateEvent = EventLiveData<Boolean>(SEND_ONCE, false)
//......
}
Second, register your observer in suitable place.
EventPool.userInfoShouldUpdateEvent.observe(owner) {
getUserInfo()
}
Third, set value when you want to send a event.
EventPool.userInfoShouldUpdateEvent.postValue(true)
or
EventPool.userInfoShouldUpdateEvent.value = true
If you don't need the event trigger directly, suggest call postValue
, because the setValue
would block current thread while current thread is not main thread.
If you want reset the value without event trigger, you can just call
EventPool.userInfoShouldUpdateEvent.resetValue()
That all.
The constructor of EventLiveData has two parameters:
stickyCount(Int) and activeForever(Boolean)
If stickyCount more than zero, the meaning of stickyCount is the left count for sending sticky event.
If stickyCount value is EventLiveData.NO_STICKY
means that the event of this EventLiveData would send is not sticky event.
If stickyCount value is EventLiveData.STICKY_FOREVER
means that the event of this EventLiveData would send is sticky event.
If stickyCount value is EventLiveData.SEND_ONCE
means that the event of this EventLiveData would send just will send once.
Whether the event should be send or not while the LifCycleOwner which subscribed this EventLiveData is in invisiable state.