Skip to content

Instantly share code, notes, and snippets.

@PierceZ
Created September 20, 2017 12:59
Show Gist options
  • Save PierceZ/2f688fc6083b9376803e76b15347998c to your computer and use it in GitHub Desktop.
Save PierceZ/2f688fc6083b9376803e76b15347998c to your computer and use it in GitHub Desktop.
Another approach to a LiveData event bus. Where each LiveData instance is tied to a lifecycle.
public final class LiveDataBus {
private static SparseArray<Map<LifecycleRegistryOwner, EventLiveData>> sSubjectMap = new SparseArray<>();
public static final int SUBJECT_DATA_LOADED = 0, SUBJECT_DOWNLOAD_COMPLETE = 1;
@Retention(SOURCE)
@IntDef({SUBJECT_DATA_LOADED, SUBJECT_DOWNLOAD_COMPLETE})
@interface Subject {
}
private LiveDataBus() {
// hidden constructor
}
/**
* Gets a map which has a LifecycleRegistryOwner for each EventLiveData, for a specific subject. So each lifecycle has
* its own EventLiveData.
*/
private static Map<LifecycleRegistryOwner, EventLiveData> getLiveDataMap(@Subject int subjectCode) {
Map<LifecycleRegistryOwner, EventLiveData> liveDataMap = sSubjectMap.get(subjectCode);
if (liveDataMap == null) {
liveDataMap = new HashMap<>();
sSubjectMap.put(subjectCode, liveDataMap);
}
return liveDataMap;
}
/**
* Get the live data or create it if it's not already in memory.
*/
@NonNull
private static EventLiveData getLiveData(@Subject int subjectCode, @NonNull LifecycleRegistryOwner lifecycle) {
Map<LifecycleRegistryOwner, EventLiveData> liveDataMap = getLiveDataMap(subjectCode);
EventLiveData liveData = liveDataMap.get(lifecycle);
if (liveData == null) {
liveData = new EventLiveData(subjectCode, lifecycle);
liveDataMap.put(lifecycle, liveData);
}
return liveData;
}
/**
* Subscribe to the specified subject and listen for updates on that subject.
*/
public static void subscribe(@Subject int subject, @NonNull LifecycleRegistryOwner lifecycle, @NonNull Observer<Object> action) {
getLiveData(subject, lifecycle).observe(lifecycle, action);
}
/**
* Removes this subject when it has no observers.
*/
public static void unregister(@Subject int subject, @NonNull LifecycleRegistryOwner lifecycle) {
Map<LifecycleRegistryOwner, EventLiveData> liveDataMap = getLiveDataMap(subject);
liveDataMap.remove(lifecycle);
if (liveDataMap.size() == 0) {
sSubjectMap.remove(subject);
}
}
/**
* Publish an object to the specified subject for all subscribers of that subject.
*/
public static void publish(@Subject int subject, @NonNull Object message) {
for (EventLiveData eventLiveData : getLiveDataMap(subject).values()) {
eventLiveData.update(message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment