Newer
Older
RxFlux / app / src / main / java / j4ckall / rxflux / lib / flux / Dispatcher.java
package j4ckall.rxflux.lib.flux;

import java.util.Objects;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

/**
 * ActionをトリガーにしてdispatcherSubjectを購読しているStoreにデータを流す
 *
 * @author matsumoto_k
 */
public class Dispatcher {

    private final Subject<Action> dispatcherSubject = PublishSubject.<Action>create().toSerialized();
    private final Observable<Action> dispatch = dispatcherSubject.hide();

    public Dispatcher() {
    }

    /**
     * dispatcherSubjectを購読する
     *
     * @param key
     * @param subscriber
     * @return
     */
    final Observable<Action> on(Action.Key key, Consumer<Action> subscriber) {
        return dispatcherSubject.filter(fluxAction -> Objects.equals(fluxAction.key, key))
                .doOnNext(subscriber);
    }

    /**
     * dispatcherSubjectを購読しているStoreにデータを流す
     *
     * @param fluxAction
     */
    final void dispatch(Action fluxAction) {
        dispatcherSubject.onNext(fluxAction);
    }

    /**
     * dispatcherSubjectは公開したくない(外部からonNext出来る)ので
     * Observableに変換して返す
     *
     * @return Observable<Action>
     */
    public Observable<Action> getDispatch() {
        return dispatch;
    }
}