package com.thuytrinh.transactionviewer.products;

import com.thuytrinh.transactionviewer.api.Transaction;
import com.thuytrinh.transactionviewer.api.TransactionsFetcher;

import javax.inject.Inject;

import rx.Observable;

public class ProductRepository {
  private final TransactionsFetcher transactionsFetcher;

  @Inject ProductRepository(TransactionsFetcher transactionsFetcher) {
    this.transactionsFetcher = transactionsFetcher;
  }

  public Observable<Product> getProductsAsync() {
    return transactionsFetcher.fetchTransactionsAsync()
        .flatMap(Observable::from)
        .groupBy(Transaction::sku)
        .flatMap(x -> x
            .toList()
            .map(transactions -> ImmutableProduct.builder()
                .sku(x.getKey())
                .transactions(transactions)
                .build()
            ));
  }
}

@@ -264,53 +264,44 @@
 ate 
-final TransactionsFetcher transactionsFetcher
+Observable%3CProduct%3E getProductsAsync
 ;%0A%0A 
@@ -378,122 +378,53 @@
     
-this.transactionsFetcher = transactionsFetcher;%0A  %7D%0A%0A  public Observable%3CProduct%3E getProductsAsync() %7B%0A    return 
+getProductsAsync = Observable%0A        .defer(
 tran
@@ -438,17 +438,18 @@
 sFetcher
-.
+::
 fetchTra
@@ -462,17 +462,16 @@
 onsAsync
-(
 )%0A      
@@ -612,16 +612,26 @@
 tions -%3E
+ (Product)
  Immutab
@@ -752,16 +752,16 @@
 build()%0A
-
         
@@ -766,16 +766,117 @@
       ))
+%0A        .cache();%0A  %7D%0A%0A  public Observable%3CProduct%3E getProductsAsync() %7B%0A    return getProductsAsync
 ;%0A  %7D%0A%7D%0A

Load and cache products