In the StockDataAdapter.java file, there was a code block to avoid adding the same values that are already present in the stream:
for (StockUpdate stockUpdate : data) {
if (stockUpdate.getStockSymbol()
.equals(newStockUpdate.getStockSymbol())) {
if (stockUpdate.getPrice()
.equals(newStockUpdate.getPrice())
&& stockUpdate.getTwitterStatus()
.equals(newStockUpdate.getTwitterStatus())) {
return;
}
break;
}
}
However, it would be better to make the .add() method simpler by freeing it up from this responsibility of skipping duplicate values; now we can handle it in the flow. Let's start by extracting a method to check whether there is a duplicate value:
public void add(StockUpdate newStockUpdate) {
this.data.add(0, newStockUpdate);
notifyItemInserted(0);
}
public boolean contains(StockUpdate newStockUpdate) {
for (StockUpdate stockUpdate : data) {
if (stockUpdate.getStockSymbol()
.equals(newStockUpdate.getStockSymbol())) {
if (stockUpdate.getPrice()
.equals(newStockUpdate.getPrice())
&& stockUpdate.getTwitterStatus()
.equals(newStockUpdate.getTwitterStatus())) {
return true;
}
break;
}
}
return false;
}
Now, the .contains() method can be used in the flow to add only new, non-existing entries:
.observeOn(AndroidSchedulers.mainThread())
.filter(update -> !stockDataAdapter.contains(update))
.subscribe(stockUpdate -> {
Log.d("APP", "New update " + stockUpdate.getStockSymbol());
noDataAvailableView.setVisibility(View.GONE);
stockDataAdapter.add(stockUpdate);
recyclerView.smoothScrollToPosition(0);
}, error -> {
if (stockDataAdapter.getItemCount() == 0) {
noDataAvailableView.setVisibility(View.VISIBLE);
}
});
Note the following line:
.filter(update -> !stockDataAdapter.contains(update))
This means that no value that doesn't satisfy the condition will be let through.