package us.poitot.gridly.bus;

import javax.inject.Inject;
import javax.inject.Singleton;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;

/**
 * Event bus implemented using RxJava.
 */
@Singleton
public class EventBus {

    private final Subject<Object, Object> mSubject = new SerializedSubject<>(PublishSubject.create());

    @Inject
    public EventBus() { }

    public void post(Object o) {
        mSubject.onNext(o);
    }

    public<T> Subscription onEvent(Class<T> clazz, Action1<T> handler) {
        return mSubject.ofType(clazz).subscribe(handler);
    }

    public<T> Subscription onEventMainThread(Class<T> clazz, Action1<T> handler) {
        return mSubject.ofType(clazz).observeOn(AndroidSchedulers.mainThread()).subscribe(handler);
    }

    public boolean hasObservers() {
        return mSubject.hasObservers();
    }
}
