Newer
Older
RxFlux / app / src / main / java / j4ckall / rxflux / ui / MainStore.java
package j4ckall.rxflux.ui;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.Subject;
import j4ckall.rxflux.App;
import j4ckall.rxflux.lib.flux.Store;

/**
 * MainActivityの状態を保持するクラス
 *
 * @author matsumoto_k
 */
public class MainStore extends Store {

    private Subject<Integer> countSubject = BehaviorSubject.<Integer>create().toSerialized();
    private Observable<Integer> count = countSubject.hide().scan((sum, num) -> sum += num);
    private boolean initialize = false;

    public MainStore() {
        super(App.getDispatcher());

        getDispatchObservable(MainAction.COUNT_UP)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action -> {
                    countSubject.onNext((Integer) action.value);
                });

        getDispatchObservable(MainAction.COUNT_DOWN)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action -> {
                    countSubject.onNext((Integer) action.value);
                });

        getDispatchObservable(MainAction.INITIALIZE)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action -> {
                    if (!initialize) {
                        countSubject.onNext((Integer) action.value);
                        initialize = true;
                    }
                });

        // TODO:DispatchからObservableを受け取るのかDispatchに対してSubscriberを設定するのかどちらが良いのか調べる
//        on(MainAction.COUNT_UP, action -> {
//            countSubject.onNext((Integer) action.value);
//        });
//
//        on(MainAction.COUNT_DOWN, action -> {
//            countSubject.onNext((Integer) action.value);
//        });
//
//        on(MainAction.INITIALIZE, action -> {
//            countSubject.onNext((Integer) action.value);
//        });
    }

    public Observable<Integer> getCount() {
        return count;
    }
}