Skip to content

Instantly share code, notes, and snippets.

@PierceZ
Last active July 20, 2017 12:20
Show Gist options
  • Save PierceZ/ddb159eecfbff6fc817870d23606efa6 to your computer and use it in GitHub Desktop.
Save PierceZ/ddb159eecfbff6fc817870d23606efa6 to your computer and use it in GitHub Desktop.
public final class RxBus {
private static Map<String, PublishSubject<Object>> sSubjectMap = new HashMap<>();
private static Map<Object, CompositeDisposable> sSubscriptionsMap = new HashMap<>();
private RxBus() {
// hidden constructor
}
/**
* Get the subject or create it if it's not already in memory.
*/
@NonNull
private static PublishSubject<Object> getSubject(String subjectKey) {
PublishSubject<Object> subject = sSubjectMap.get(subjectKey);
if (subject == null) {
subject = PublishSubject.create();
subject.subscribeOn(AndroidSchedulers.mainThread());
sSubjectMap.put(subjectKey, subject);
}
return subject;
}
/**
* Get the CompositeDisposable or create it if it's not already in memory.
*/
@NonNull
private static CompositeDisposable getCompositeDisposable(@NonNull Object object) {
CompositeDisposable compositeDisposable = sSubscriptionsMap.get(object);
if (compositeDisposable == null) {
compositeDisposable = new CompositeDisposable();
sSubscriptionsMap.put(object, compositeDisposable);
}
return compositeDisposable;
}
/**
* Subscribe to the specified subject and listen for updates on that subject. Pass in an object to associate
* your registration with, so that you can unsubscribe later.
* <br/><br/>
* <b>Note:</b> Make sure to call {@link RxBus#unregister(Object)} to avoid memory leaks.
*/
public static void subscribe(@Subject int subject, @NonNull Object lifecycle, @NonNull Consumer<Object> action) {
Disposable disposable = getSubject(subject).subscribe(action);
getCompositeDisposable(lifecycle).add(disposable);
}
/**
* Unregisters this object from the bus, removing all subscriptions.
* This should be called when the object is going to go out of memory.
*/
public static void unregister(@NonNull Object lifecycle) {
//We have to remove the composition from the map, because once you dispose it can't be used anymore
CompositeDisposable compositeDisposable = sSubscriptionsMap.remove(lifecycle);
if (compositeDisposable != null) {
compositeDisposable.dispose();
}
}
/**
* Publish an object to the specified subject for all subscribers of that subject.
*/
public static void publish(String subject, @NonNull Object message) {
getSubject(subject).onNext(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment