Android导入Transformer用于Loader

时间:2017-03-22 18:30:08

标签: android

this link我读到了在电话轮换时使用RxJava并保存状态,但我在这个类的导入Transformer上有一个简单的问题:

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;

import org.reactivestreams.Subscription;

import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

public class RxLoader<T> extends Loader<T> {
    private final Observable<T> observable;
    private final BehaviorSubject<T> cache = BehaviorSubject.create();

    private Subscription subscription;

    private RxLoader(Context context, Observable<T> observable) {
        super(context);
        this.observable = observable;
    }

    public static <T> Observable.Transformer<T, T> compose(AppCompatActivity activity, int id) {
        return observable -> create(activity, id, observable);
    }


    public static <T> Observable<T> create(AppCompatActivity activity, int id,
                                           Observable<T> observable) {
        LoaderManager loaderManager = activity.getSupportLoaderManager();

        CreateLoaderCallback<T> createLoaderCallback =
                new CreateLoaderCallback<>(activity, observable);
        loaderManager.initLoader(id, null, createLoaderCallback);

        RxLoader<T> rxLoader = (RxLoader<T>) loaderManager.getLoader(id);
        return rxLoader.cache.asObservable();
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        subscription = observable.subscribe(cache::onNext);
    }

    @Override
    protected void onReset() {
        super.onReset();
        subscription.unsubscribe();
    }

    private static class CreateLoaderCallback<T>
            implements LoaderManager.LoaderCallbacks<T> {

        private final Context context;
        private final Observable<T> observable;

        public CreateLoaderCallback(Context context, Observable<T> observable) {
            this.context = context;
            this.observable = observable;
        }

        @Override
        public Loader<T> onCreateLoader(int id, Bundle args) {
            return new RxLoader<>(context, observable);
        }

        @Override
        public void onLoadFinished(Loader<T> loader, T data) { }

        @Override
        public void onLoaderReset(Loader<T> loader) { }
    }
}

问题出现在课程的这一部分:

public static <T> Observable.Transformer<T, T> compose( ...

1 个答案:

答案 0 :(得分:0)

您最有可能导入的代码是使用RxJava 1实现的。

您有两种选择:

  • 导入RxJava 1而不是RxJava 2
  • 将现有代码转换为RxJava 2&#39; s ObserverTransformer