从java.lang.Observable迁移到RxJava

时间:2016-04-25 11:44:54

标签: java android rx-java

我正在使用具有购物车的Android应用程序。 Cart对象扩展java.lang.Observable,因此如果有任何更改,它们会立即保存到磁盘中,以便更新徽章图标。

public class Cart extends Observable{

    private Set<Product> products;

    public Cart(){
        products = new HashSet<>();
    }

    public Cart(Collection<Product> products){
        this.products = new HashSet<>(products);
    }

    public int getTotalItems() {
        return products.size();
    }

    public void clear(){
        products.clear();
        setChanged();
        notifyObservers();
    }

    public void addProduct(Product product){
        products.add(product);
        setChanged();
        notifyObservers();
    }

    public void removeProduct(Product product){
        products.remove(product);
        setChanged();
        notifyObservers();
    }

    public void updateProduct(Product product){
        products.remove(product);
        products.add(product);
        setChanged();
        notifyObservers();
    }

    public List<Product> getProducts() {
        return new ArrayList<>(products);
    }
}

使用示例

public class MainActivity extends BaseActivity implements Observer {
    Cart mCart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        getApp().getCart().addObserver(this);
        setCartItemsCount(getApp().getCart().getTotalItems());

        //...
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (getApp().getCart() != null) {
            getApp().getCart().deleteObserver(this);
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        if (observable instanceof Cart) {
            setCartItemsCount(((Cart) observable).getTotalItems());
        }
    }
}

我想将此代码迁移到RxJava,但我对如何处理它并不清楚。从我读到的内容来看,我应该使用BehavioralSubject,但我不知道如何调整我已经阅读过的示例。

如果有一些指导或示例,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

我做了一些小例子,可以帮助你理解这个想法。 我已使用此库https://github.com/trello/RxLifecycle,我还建议您使用此http://google.github.io/dagger/

public class MainActivity extends RxActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final CartPresenter cartPresenter = new CartPresenter();
    final TextView counterTextView = (TextView) findViewById(R.id.counter);
    final Button button = (Button) findViewById(R.id.button2);

    RxView.clicks(button)
            .subscribe(new Action1<Void>() {
                @Override
                public void call(Void aVoid) {
                    cartPresenter.getCardModel().addProduct(new Random().nextInt(100));
                }
            });

    cartPresenter.getCardObservable()
            .compose(this.<CartPresenter.CardModel>bindToLifecycle())
            .subscribe(new Action1<CartPresenter.CardModel>() {
                @Override
                public void call(CartPresenter.CardModel cardModel) {
                    counterTextView.setText(String.valueOf(cardModel.getProducts().size()));
                }
            });
}
}

一个简单易懂的初学者解决方案

public class CartPresenter {

    private final PublishSubject<CardModel> dataChangedSubject = PublishSubject.create();
    private final Observable<CardModel> cardObservable;
    private final CardModel cardModel;

    public CartPresenter() {
        cardModel = new CardModel();

        this.cardObservable = dataChangedSubject.startWith(cardModel)
                .flatMap(new Func1<CardModel, Observable<CardModel>>() {
                    @Override
                    public Observable<CardModel> call(CardModel cardModel) {
                        return Observable.just(cardModel);
                    }
                });
    }

    public CardModel getCardModel() {
        return cardModel;
    }

    @NonNull
    public Observable<CardModel> getCardObservable() {
        return cardObservable;
    }

    class CardModel {
        final private Set<Integer> products;

        public CardModel() {
            this.products = new HashSet<>();
        }

        public void addProduct(Integer integer) {
            products.add(integer);
            dataChangedSubject.onNext(this);
        }

        public Set<Integer> getProducts() {
            return products;
        }
    }
}

对于一些更高级的用户

public class CartPresenter {

    private final PublishSubject<CardModel> dataChangedSubject = PublishSubject.create();
    private final Observable<CardModel> cardObservable;
    private final CardModel cardModel;

    public CartPresenter() {
        cardModel = new CardModel();

        this.cardObservable = Observable.just(cardModel)
                .compose(new Observable.Transformer<CardModel, CardModel>() {
                    @Override
                    public Observable<CardModel> call(final Observable<CardModel> cardModelObservable) {
                        return dataChangedSubject.switchMap(new Func1<Object, Observable<? extends CardModel>>() {
                            @Override
                            public Observable<? extends CardModel> call(Object o) {
                                return cardModelObservable;
                            }
                        });
                    }
                });

    }

    public CardModel getCardModel() {
        return cardModel;
    }

    @NonNull
    public Observable<CardModel> getCardObservable() {
        return cardObservable;
    }

    class CardModel {
        final private Set<Integer> products;

        public CardModel() {
            this.products = new HashSet<>();
        }

        public void addProduct(Integer integer) {
            products.add(integer);
            dataChangedSubject.onNext(null);
        }

        public Set<Integer> getProducts() {
            return products;
        }
    }
}