I'm working on an Android application that features a shopping cart. The Cart object extends java.lang.Observable so if there are any changes, they are saved to the disk immediately and also so that the badge icon can be updated.
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);
}
}
Example usage
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());
}
}
}
I'd like to migrate this code to RxJava but i don't have a clear idea on how to go about it. From what I read, I'm supposed to use BehavioralSubject but I don't know how to adapt the examples I've read to my scenario.
I would appreciate if some guidance or an example.