是否有可能使Realm成为观察者?

时间:2016-10-01 10:37:55

标签: realm observer-pattern

Realm将观察webservice,并且可以观察UI。

container_of

1 个答案:

答案 0 :(得分:0)

Reactive Pattern,Presenter

来自resume()的第一次来电:

public void fetchCompanies(Context context) {

    unsubscribeAll();
    if (Utils.isNetworkAvailable(context)) {
        subscribe(mCompanyViewListener.getCompanies(), this);
    } else {
        Realm realm = Realm.getDefaultInstance();


        realm.where(Company.class).findAll().asObservable()
                .map(new Func1<RealmResults<Company>, Observable<Result<Company>>>() {
                    @Override
                    public Observable<Result<Company>> call(RealmResults<Company> companies) {
                        Result<Company> companyResult = new Result<>();
                        companyResult.setValue(companies);
                        return Observable.just(companyResult);
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Observable<Result<Company>>>() {
            @Override
            public void call(Observable<Result<Company>> companyResult) {
                subscribe(companyResult, CompanyPresenter.this);
            }
        });
    }
}

第二,当服务上有可观察的

@Override
public void onCompanies(Result<Company> companies) {
    realm.beginTransaction();
    realm.insertOrUpdate(companies.getValue());
    realm.commitTransaction();

    mCompanyAdapter.addCompanies(realm.where(Company.class).findAll());
    mProgressDialog.dismiss();
}

取消

@Override
    public void onDestroy() {
        unsubscribeAll();
    }