Last active
August 8, 2016 15:45
-
-
Save davinctor/51426051b4ce7182209ef5b9a25d710e to your computer and use it in GitHub Desktop.
Implementation of bus with RxJava with simple example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* After receiving {@link FetchPointsRxEvent} receiver must to update views with points count | |
* | |
* 21.04.16 | |
* Created by Victor Ponomarenko | |
*/ | |
public class FetchPointsRxEvent { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 21.04.16 | |
* Created by Victor Ponomarenko | |
*/ | |
public final class RxBus { | |
private final Subject<Object, Object> bus = new SerializedSubject<>(PublishSubject.create()); | |
public static RxBus instance() { | |
return Loader.INSTANCE; | |
} | |
public void send(Object o) { | |
bus.onNext(o); | |
} | |
private Observable<Object> toObservable() { | |
return bus; | |
} | |
@SuppressWarnings("unchecked cast") | |
public <T> Observable<T> filter(final Class<T> eventClass){ | |
return toObservable() | |
.filter(event-> event.getClass().equals(eventClass)) | |
.map(event-> (T)event); | |
} | |
private static final class Loader { | |
private static final RxBus INSTANCE = new RxBus(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Send event | |
onEvent(BindState.BOUND) | |
.flatMap(boundState -> view().onEvent(FragmentState.CREATED)) | |
.subscribe(createState -> { | |
RxBus.instance().send(new FetchPointsRxEvent()); | |
}); | |
// Subscribe to event | |
RxBus.instance().filter(FetchPointsRxEvent.class) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.compose(bindUntil(BindState.UNBOUND)) | |
.compose(view().bindUntil(ActivityState.DESTROYED)) | |
.subscribe(event -> { | |
Log.i(TAG, "fetchPoints"); | |
fetchUserPoints(); | |
}, Throwable::printStackTrace); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment