package com.davidemortara.reactmvvm.viewmodel;

import android.support.annotation.NonNull;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.BehaviorSubject;

public abstract class BaseViewModel implements IBaseViewModel {

    @NonNull
    public final BehaviorSubject<Boolean> isActive = BehaviorSubject.create();
    private CompositeDisposable compositeDisposable;

    @Override
    public void activated() {
        isActive.onNext(true);
        bind();
    }

    //region rx

    @Override
    public void deactivated() {
        isActive.onNext(false);
        unbind();
    }

    private void bind() {
        unbind();
        compositeDisposable = new CompositeDisposable();
        registerRules();
    }

    private void unbind() {
        if (compositeDisposable != null) {
            compositeDisposable.clear();
        }
    }

    protected void register(Disposable disposable) {
        compositeDisposable.add(disposable);
    }

    protected abstract void registerRules();

    //endregion
}

{'avg_line_length': 22.367346938775512, 'max_line_length': 78, 'alphanum_fraction': 0.676094890510949, 'licenses': ['Apache-2.0'], 'repository_name': 'basettoni89/ReactMovies', 'path': 'reactmvvm/src/main/java/com/davidemortara/reactmvvm/viewmodel/BaseViewModel.java', 'size': 1096, 'lang': 'Java'}