Skip to content

Instantly share code, notes, and snippets.

@ar-android
Forked from vuhung3990/RxBus.java
Created February 13, 2017 08:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ar-android/8afe5eb6efba714bf3a9b806a9841d90 to your computer and use it in GitHub Desktop.
Save ar-android/8afe5eb6efba714bf3a9b806a9841d90 to your computer and use it in GitHub Desktop.
Rxjava 2 Bus
dependencies {
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
}
/**
* for send object between fragment, activity, service...
* REMEMBER: dispose if not in use to avoid leak memory
*/
public class RxBus<T> {
private static final String PREFIX = "$^%)@";
private static RxBus instance;
private PublishSubject<BusMessage<T>> subject = PublishSubject.create();
public static RxBus getInstance() {
if (instance == null) {
instance = new RxBus();
}
return instance;
}
/**
* send message with chanel to receive
*
* @param chanel to filter between multiple object sent
* @param message
* @see #getMessages(String)
*/
public void sendMessage(String chanel, T message) {
subject.onNext(new BusMessage<T>(chanel, message));
}
/**
* @param chanel to filter between multiple object sent
* @return Observable object with chanel filter
* @see #sendMessage(String, Object)
*/
public Observable<T> getMessages(String chanel) {
return subject
.filter(tBusMessage -> tBusMessage.chanel == chanel) // filter by chanel
.map(tBusMessage -> tBusMessage.value); // custom output (remove chanel+prefix string)
}
/**
* message object to send
* @param <T>
*/
class BusMessage<T> {
String chanel;
T value;
public BusMessage(String key, T value) {
this.chanel = key;
this.value = value;
}
}
}
// unsubscribe if not in use
protected void onPause() {
super.onPause();
unsubscriber.dispose();
}
protected void onResume() {
super.onResume();
unsubscriber = RxBus.getInstance()
.getMessages(ContactAdapter.ON_CONTACT_CLICK)
.subscribe(onContactClick());
}
private Consumer<Contact> onContactClick() {
return contact -> {
LogUtils.print(contact.getName()+","+contact.getNumbers());
};
}
/// send message from adapter
itemHolder.itemView.setOnClickListener(view -> RxBus.getInstance().sendMessage(ON_CONTACT_CLICK, contact));
/// you can send any type of object: String, Integer, Object class... => create Consumer<YOUR_TYPE> on .subscribe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment