Giter Site home page Giter Site logo

store's Introduction

DEPRECATED

Store(3) is deprecated. No more development will be taking place. For an up-to-date version, please use Store(4). Thanks for all your support!


Build Status

Store Logo

Store is a Java library for effortless, reactive data loading.

The Problems:

  • Modern software needs data representations to be fluid and always available.
  • Users expect their UI experience to never be compromised (blocked) by new data loads. Whether an application is social, news, or business-to-business, users expect a seamless experience both online and offline.
  • International users expect minimal data downloads as many megabytes of downloaded data can quickly result in astronomical phone bills.

A Store is a class that simplifies fetching, parsing, storage, and retrieval of data in your application. A Store is similar to the Repository pattern [https://msdn.microsoft.com/en-us/library/ff649690.aspx] while exposing a Reactive API built with RxJava that adheres to a unidirectional data flow.

Store provides a level of abstraction between UI elements and data operations.

Overview

A Store is responsible for managing a particular data request. When you create an implementation of a Store, you provide it with a Fetcher, a function that defines how data will be fetched over network. You can also define how your Store will cache data in-memory and on-disk, as well as how to parse it. Since Store returns your data as an Observable, threading is a breeze! Once a Store is built, it handles the logic around data flow, allowing your views to use the best data source and ensuring that the newest data is always available for later offline use. Stores can be customized to work with your own implementations or use our included middleware.

Store leverages RxJava and multiple request throttling to prevent excessive calls to the network and disk cache. By utilizing Store, you eliminate the possibility of flooding your network with the same request while adding two layers of caching (memory and disk).

How to include in your project

Include gradle dependency
implementation 'com.nytimes.android:store3:3.1.1'
Set the source & target compatibilities to 1.8

Starting with Store 3.0, retrolambda is no longer used. Therefore to allow support for lambdas the Java sourceCompatibility and targetCompatibility need to be set to 1.8

android {
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
    ...
}

Fully Configured Store

Let's start by looking at what a fully configured Store looks like. We will then walk through simpler examples showing each piece:

Store<ArticleAsset, Integer> articleStore = StoreBuilder.<Integer, BufferedSource, ArticleAsset>parsedWithKey()
        .fetcher(articleId -> api.getArticleAsBufferedSource(articleId))  // OkHttp responseBody.source()
        .persister(FileSystemPersister.create(FileSystemFactory.create(context.getFilesDir()), pathResolver))
        .parser(GsonParserFactory.createSourceParser(gson, ArticleAsset.Article.class))
        .open();
        

With the above setup you have:

  • In-memory caching for rotation
  • Disk caching for when users are offline
  • Parsing through streaming API to limit memory consumption
  • Rich API to ask for data whether you want cached, new or a stream of future data updates.

And now for the details:

Creating a Store

You create a Store using a builder. The only requirement is to include a Fetcher<ReturnType, KeyType> that returns a Single<ReturnType> and has a single method fetch(key)

Store<ArticleAsset, Integer> store = StoreBuilder.<>key()
        .fetcher(articleId -> api.getArticle(articleId))  // OkHttp responseBody.source()
        .open();

Stores use generic keys as identifiers for data. A key can be any value object that properly implements toString(), equals() and hashCode(). When your Fetcher function is called, it will be passed a particular Key value. Similarly, the key will be used as a primary identifier within caches (Make sure to have a proper hashCode()!!).

Our Key implementation - Barcodes

For convenience, we included our own key implementation called a BarCode. Barcode has two fields String key and String type

BarCode barcode = new BarCode("Article", "42");

When using a Barcode as your key, you can use a StoreBuilder convenience method

Store<ArticleAsset, BarCode> store = StoreBuilder.<ArticleAsset>barcode()
        .fetcher(articleBarcode -> api.getAsset(articleBarcode.getKey(), articleBarcode.getType()))
        .open();

Public Interface - Get, Fetch, Stream, GetRefreshing

Single<Article> article = store.get(barCode);

The first time you subscribe to store.get(barCode), the response will be stored in an in-memory cache. All subsequent calls to store.get(barCode) with the same Key will retrieve the cached version of the data, minimizing unnecessary data calls. This prevents your app from fetching fresh data over the network (or from another external data source) in situations when doing so would unnecessarily waste bandwidth and battery. A great use case is any time your views are recreated after a rotation, they will be able to request the cached data from your Store. Having this data available can help you avoid the need to retain this in the view layer.

So far our Store’s data flow looks like this: Simple Store Flow

By default, 100 items will be cached in memory for 24 hours. You may pass in your own instance of a Guava Cache to override the default policy.

Busting through the cache

Alternatively you can call store.fetch(barCode) to get an Observable that skips the memory (and optional disk cache).

Fresh data call will look like: store.fetch() Simple Store Flow

In the New York Times app, overnight background updates use fetch() to make sure that calls to store.get() will not have to hit the network during normal usage. Another good use case for fetch() is when a user wants to pull to refresh.

Calls to both fetch() and get() emit one value and then call onCompleted() or throw an error.

Stream

For real-time updates, you may also call store.stream() which returns an Observable that emits each time a new item is added to the Store. You can think of stream as an Event Bus-like feature that allows you to know when any new network hits happen for a particular Store. You can leverage the Rx operator filter() to only subscribe to a subset of emissions.

Get Refreshing

There is another special way to subscribe to a Store: getRefreshing(key). This method will subscribe to get() which returns a single response, but unlike get(), getRefreshing(key) will stay subscribed. Anytime you call store.clear(key) anyone subscribed to getRefreshing(key) will resubscribe and force a new network response.

Inflight Debouncer

To prevent duplicate requests for the same data, Store offers an inflight debouncer. If the same request is made within a minute of a previous identical request, the same response will be returned. This is useful for situations when your app needs to make many async calls for the same data at startup or when users are obsessively pulling to refresh. As an example, The New York Times news app asynchronously calls ConfigStore.get() from 12 different places on startup. The first call blocks while all others wait for the data to arrive. We have seen a dramatic decrease in the app's data usage after implementing this inflight logic.

Adding a Parser

Since it is rare for data to arrive from the network in the format that your views need, Stores can delegate to a parser by using a StoreBuilder.<BarCode, BufferedSource, Article>parsedWithKey()

Store<Article, Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey()
        .fetcher(articleId -> api.getArticle(articleId)) 
        .parser(source -> {
            try (InputStreamReader reader = new InputStreamReader(source.inputStream())) {
                return gson.fromJson(reader, Article.class);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        })
        .open();

Our updated data flow now looks like this:

store.get() -> Simple Store Flow

Middleware - GsonSourceParser

There are also separate middleware libraries with parsers to help in cases where your fetcher is a Reader, BufferedSource or String and your parser is Gson:

  • GsonReaderParser
  • GsonSourceParser
  • GsonStringParser

These can be accessed via a Factory class (GsonParserFactory).

Our example can now be rewritten as:

Store<Article, Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey()
        .fetcher(articleId -> api.getArticle(articleId)) 
        .parser(GsonParserFactory.createSourceParser(gson, Article.class))
        .open();

In some cases you may need to parse a top level JSONArray, in which case you can provide a TypeToken.

Store<List<Article>, Integer> store = StoreBuilder.<Integer, BufferedSource, List<Article>>parsedWithKey()
        .fetcher(articleId -> api.getArticles()) 
        .parser(GsonParserFactory.createSourceParser(gson, new TypeToken<List<Article>>() {}))
        .open();  

Similarly we have a middleware artifact for Moshi & Jackson too!

Disk Caching

Stores can enable disk caching by passing a Persister into the builder. Whenever a new network request is made, the Store will first write to the disk cache and then read from the disk cache.

Now our data flow looks like: store.get() -> Simple Store Flow

Ideally, data will be streamed from network to disk using either a BufferedSource or Reader as your network raw type (rather than String).

Store<Article, Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey()
        .fetcher(articleId -> api.getArticles())
        .persister(new Persister<BufferedSource>() {
            @Override
            public Maybe<BufferedSource> read(Integer key) {
                if (dataIsCached) {
                    return Observable.fromCallable(() -> userImplementedCache.get(key));
                } else {
                    return Observable.empty();
                }    
            }
    
            @Override
            public Single<Boolean> write(BarCode barCode, BufferedSource source) {
                userImplementedCache.save(key, source);
                return Single.just(true);
            }
        })
        .parser(GsonParserFactory.createSourceParser(gson, Article.class))
        .open();

Stores don’t care how you’re storing or retrieving your data from disk. As a result, you can use Stores with object storage or any database (Realm, SQLite, CouchDB, Firebase etc). The only requirement is that data must be the same type when stored and retrieved as it was when received from your Fetcher. Technically, there is nothing stopping you from implementing an in memory cache for the “persister” implementation and instead have two levels of in memory caching--one with inflated and one with deflated models, allowing for sharing of the “persister” cache data between stores.

Note: When using a Parser and a disk cache, the Parser will be called AFTER fetching from disk and not between the network and disk. This allows your persister to work on the network stream directly.

If using SQLite we recommend working with SqlBrite. If you are not using SqlBrite, an Observable can be created rather simply with Observable.fromCallable(() -> getDBValue())

Middleware - SourcePersister & FileSystem

We've found the fastest form of persistence is streaming network responses directly to disk. As a result, we have included a separate library with a reactive FileSystem which depends on Okio BufferedSources. We have also included a FileSystemPersister which will give you disk caching and works beautifully with GsonSourceParser. When using the FileSystemPersister you must pass in a PathResolver which will tell the file system how to name the paths to cache entries.

Now back to our first example:

Store<Article, Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey()
        .fetcher(articleId -> api.getArticles(articleId)) 
        .persister(FileSystemPersister.create(FileSystemFactory.create(context.getFilesDir()), pathResolver))
        .parser(GsonParserFactory.createSourceParser(gson, String.class))
        .open();

As mentioned, the above builder is how we work with network operations at the New York Times. With the above setup you have:

  • Memory caching with Guava Cache
  • Disk caching with FileSystem (you can reuse the same file system implementation for all stores)
  • Parsing from a BufferedSource (to an Article in our case) with Gson
  • In-flight request management
  • Ability to get cached data or bust through your caches (get() vs. fetch())
  • Ability to listen for any new emissions from network (stream)
  • Ability to be notified and resubscribed when caches are cleared (helpful for times when you need to do a POST request and update another screen, such as with getRefreshing())

We recommend using the above builder setup for most Stores. The SourcePersister implementation has a tiny memory footprint because it will stream bytes from network to disk and then from disk to parser. The streaming nature of Stores allows us to download dozens of 1mb+ json responses without worrying about OOM on low-memory devices. As mentioned above, Stores allow us to do things like calling configStore.get() a dozen times asynchronously before our Main Activity finishes loading without blocking the main thread or flooding our network.

RecordProvider

If you'd like your Store to know about disk data staleness, you can have your Persister implement RecordProvider. After doing so you can configure your Store to work in one of two ways:

store = StoreBuilder.<BufferedSource>barcode()
                .fetcher(fetcher)
                .persister(persister)
                .refreshOnStale()
                .open();

refreshOnStale() will backfill the disk cache anytime a record is stale. The user will still get the stale record returned to them.

Or alternatively:

store = StoreBuilder.<BufferedSource>barcode()
                .fetcher(fetcher)
                .persister(persister)
                .networkBeforeStale()
                .open();

networkBeforeStale() - Store will try to get network source when disk data is stale. If the network source throws an error or is empty, stale disk data will be returned.

Subclassing a Store

We can also subclass a Store implementation (RealStore<T>):

public class SampleStore extends RealStore<String, BarCode> {
    public SampleStore(Fetcher<String, BarCode> fetcher, Persister<String, BarCode> persister) {
        super(fetcher, persister);
    }
}

Subclassing is useful when you’d like to inject Store dependencies or add a few helper methods to a store:

public class SampleStore extends RealStore<String, BarCode> {
   @Inject
   public SampleStore(Fetcher<String, BarCode> fetcher, Persister<String, BarCode> persister) {
        super(fetcher, persister);
    }
}

Artifacts

CurrentVersion = 3.1.1

  • Cache Cache extracted from Guava (keeps method count to a minimum)

    implementation 'com.nytimes.android:cache3:CurrentVersion'
  • Store This contains only Store classes and has a dependency on RxJava + the above cache.

    implementation 'com.nytimes.android:store3:CurrentVersion'
  • Store-Kotlin Store plus a couple of added Kotlin classes for more idiomatic usage.

    implementation 'com.nytimes.android:store-kotlin3:CurrentVersion'
  • Middleware Sample Gson parsers, (feel free to create more and open PRs)

    implementation 'com.nytimes.android:middleware3:CurrentVersion'
  • Middleware-Jackson Sample Jackson parsers, (feel free to create more and open PRs)

    implementation 'com.nytimes.android:middleware-jackson3:CurrentVersion'
  • Middleware-Moshi Sample Moshi parsers, (feel free to create more and open PRs)

    implementation 'com.nytimes.android:middleware-moshi3:CurrentVersion'
  • File System Persistence Library built using Okio Source/Sink + Middleware for streaming from Network to FileSystem

    implementation 'com.nytimes.android:filesystem3:CurrentVersion'

Sample Project

See the app for example usage of Store. Alternatively, the Wiki contains a set of recipes for common use cases

  • Simple Example: Retrofit + Store
  • Complex Example: BufferedSource from Retrofit (Can be OkHttp too) + our FileSystem + our GsonSourceParser

Talks

Community projects

store's People

Contributors

alexio avatar aminelaadhari avatar ankitpagalguy avatar brianplummer avatar cemore2048 avatar charbgr avatar ctborg avatar cybo42 avatar digitalbuddha avatar eneim avatar fabiocollini avatar jeremy-techson avatar jogan avatar kevcron avatar maksim-m avatar michaldrabik avatar nightlynexus avatar paulwoitaschek avatar pavelsynek avatar pavlospt avatar ramonaharrison avatar scottroemeschke avatar shunyy avatar stefma avatar stoyicker avatar tairrzayev avatar tasomaniac avatar tkindy avatar wdziemia avatar ychescale9 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

store's Issues

MO no op MO problems

#149 raises another interesting issue. If the mem cache is less than a minute the in flight denouncer also needs to be adjusted. Secondly the no op persister needs to be migrated to use a guava cache which has same policy as mem cache.

Add ClearDisk interface

in conjunction with #68 we should have a way to clear memory and disk cache. Current idea is add:

Store:
void clear(BarCode barCode);
Builder:
builder.diskClearer(barcode->//deletes entry from user's persister);

Example about cache first then network

Thanks for creating a great library.

I have a use case that show cache data first and then get data from network in order to show latest data. May I ask how to implement this requirement using Store?

Thanks.

Pure java library?

If I see correctly there is no dependency on the Android SDK. Why isn't it a pure java library?

When I want to experiment with the store I usually just want to fire up intellij and test things on my local machine without the need of a device.

Store.clear() doesn't work as expected

When a Store's Persister is Clearable a call to store.clear() does not work as expected.

Expected behavior:
store.clear() will call persister.clear(key) for any key that was ever saved through the store.

Actual Behavior:
store.clear() will call persister.clear(key) for only the keys that are currently cached in memory.

The problem is that there is no good way to know what keys the user supplied persister is using.

Need to find a clever solution.

Store 2.0 Release

Major Changes:
#86 Migrate Barcode to any Type
#68 Refresh on Clear Transformer
#102 Add clear disk interface
#104 Stale Record for backfilling cache

Get: Threading issue due to direct call to memCache

For me the store does not work.

If I understand correctly multiple calls to get() with the same barcode should only subscribe to the source observable once. But that only works if I make the calls strictly sequentially. When I call get from different places, it makes a new network call for each. This is because you immediately call

memCache.get(barCode, new Callable<Observable<Parsed>>() from

return Observable.concat(
                cache(barCode),
                fetch(barCode)
        ).take(1);

in get. Here is a failing testcase

import com.nytimes.android.external.store.base.Store
import com.nytimes.android.external.store.base.impl.BarCode
import com.nytimes.android.external.store.base.impl.StoreBuilder
import org.junit.Before
import org.junit.Test
import rx.Observable

class Test {

    var networkCalls = 0
    lateinit var store: Store<Unit>

    @Before fun setup() {
        networkCalls = 0
        store = StoreBuilder.builder<Unit>()
                .fetcher {
                    Observable.fromCallable {
                        networkCalls++
                        Unit
                    }
                }
                .open()
    }

    @Test fun sequentially() {
        val b = BarCode("one", "two")
        store.get(b).test().awaitTerminalEvent()
        store.get(b).test().awaitTerminalEvent()

        check(networkCalls == 1) { "there are $networkCalls networkCalls" }
    }

    @Test fun parallel() {
        val b = BarCode("one", "two")
        val first = store.get(b)
        val second = store.get(b)

        first.test().awaitTerminalEvent()
        second.test().awaitTerminalEvent()

        check(networkCalls == 1) { "there are $networkCalls networkCalls" }
    }
}

Simplify Store.types()

The whole passing in types as class tokens ended up being messier than I would have hoped. Will instead create generic methods for store builder.

Store caches errors

I'm not sure if this is intended behavior. If an Observable errors, subsequent calls to get just repeat that error.
I would expect the store to retry after an error.

public class DontCacheErrorsTest {

    private boolean shouldThrow;
    private Store<Integer> store;

    @Before
    public void setUp() {
        store = StoreBuilder.<Integer>builder()
                .fetcher(barCode -> Observable.fromCallable(() -> {
                    if (shouldThrow) throw new RuntimeException();
                    else return 0;
                }))
                .open();
    }

    @Test
    public void testStoreDoesntCacheErrors() throws InterruptedException {
        BarCode barcode = new BarCode("bar", "code");

        shouldThrow = true;
        store.get(barcode).test()
                .awaitTerminalEvent()
                .assertError(Exception.class);

        shouldThrow = false;
        store.get(barcode).test()
                .awaitTerminalEvent()
                .assertNoErrors();
    }
}

Add resolver to file system

Since users can supply their own type for the Key (instead of Barcode), we need to make sure any key being created implements an String id() so that the file system will know how to turn the key into a filename. Ideally this is only a requirement if using the FileSystem

Documentation Update

Now that we have 3 middleware packages. We should update the Readme to show all 3.

We should also start thinking of making a wiki with common examples and recipes.
One for each type of middleware
Store with no persister or parser.
Store with middleware plus custom parser (multiparser)
Store with sql persister
Example using Stream/fetch/get.
Example with okhttp
Example with top level JsonAdapter
Example with barcode subclass
Example with custom memory cache builder

RxJava 2 support?

This is a pretty sweet little library, it's very similar to something I've been working on myself.
But RxJava 1 would makes me sad when inter-oping with the rest of my application code.

Any plans to update to RxJava 2?

The signifigant performance gains, Reactive Streams spec compliance, and Flowable vs Observable distinction alone makes it worth updating imo.

I would be willing to contribute or start a PR if there is interest.

Feed Key into Parser

Current Parser implementation does not take the Key as an input. There are times when parsing logic is dependent on some request param ie type. The proposal is to create a new Parser
KeyParseFunc<Key,Raw,Parsed> implements Func2<Key,Raw,Parsed> {
this way you can do

StoreBuilder.<Key,Parsed>key()
.fetcher(fetcher)
.keyParser(new Func2...)
.build()

Versioning history deleted

I saw you deleted the version history for 1.0.0 and 1.0.1. It would be great if you could keep old versions intact so its easier to follow the progress and track issues.

paginate data

thanks for your great library

can you update example to paginate data ?

Saving via Store

Hello, now i can get, fetch or stream data. How need saving or updating my data if i using your Store for retrieve it?

Create Moshi & Jackson Middleware

Following same structure as current Middleware it would be nice to also have 2 additional modules: middleware-jackson and Middleware-moshi. We will add this eventually and welcome an external contribution.

Fix store.stream(key)

I'd like to undeprecate Observable stream(V id). The adjusted functionality will be an endless stream that emits new network values coming through a store for a particular barcode. Stream allows you to stay subscribed in many places and then calling fetch(key) to get them all a new value. Implementation will be similar to getRefreshing but will instead hook into new network values.

The difference between getRefreshing(key) & stream(key) is that getRefreshing will repeat when clear is called while stream will repeat when anything hits the fetcher again.

Put 1 minute in flighter back in

Per the readme the inflight debouncer should return same result if same request made within 1 minute of each other. This logic got pulled out in error. #89 surfaced the need for it again.

Allow multiple parsers.

Currently you can only pass in a single parser. There are times when I want to use a Middleware parse plus add additional parser.

Ideally I should be able to do:
Builder.fetcher().parser(firstParser).parser(secondParser).build()

A solution should be found that does not require any additional generics while allowing any number of parsers to be used in serial.

Add record for File System

A Record represents metadata about a stored object, kind of like a java 'File'
or 'stat' in a unix filesystem. The idea here is to allow you to get info like
last modified time without actually reading the file's contents.

Parser from disk but not from fetcher

It would be very useful if one could get results from an API: eg. Stock stock = YahooFinance.get("NVDA"); Then persist that to disk using SourcePersisterFactory as a Json, then parse the result as it comes back from the disk.

Change Request: Consider migrating Barcode to a Barcode<T>

I find the BarCode class very limiting, because:

  • A String,String key value type rarely matches my key type
  • Its not type safe. If you just have a single int as a key you need to remember to set it as the string value of the key and follow that convention. When you need for example an int, the Integer.parseInt() makes it even more dangerous

I suggest to replace the BarCode class completely with generics.

Then the sample would just look like:

  private Store<RedditData, String> provideRedditStore() {
    return StoreBuilder.<RedditData, String>builder()
      .fetcher(key -> provideRetrofit().fetchSubreddit(key, "10"))
      .open();
  }

  public void loadPosts() {
    String awwRequest = "aww";
    provideRedditStore()
      .get(awwRequest)
      .flatMap(this::sanitizeData)
      .toList()
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(this::showPosts, throwable -> {
        Log.e(StoreActivity.class.getSimpleName(), throwable.getMessage(), throwable);
      });
  }

Feature Request: Use Single<T> where appropriate

I'm not sure but it seems to me that for certain operations there are more appropriate reactive base types that would make the API more fluently.

One candidate:
Store.get(barcode : Barcode) : Observable<T>
here a Single<T> would clearly indicate that its always just a single item that is being emitted.

RxJava 2

It would be great to have support for RxJava 2.

Clear Memory Fails

After clearing the memory a following call to get should make a new request. But it doesn't

See #95

Repeat When Clear functionality

Update/EDIT:
It would be nice to have a repeat when functionality where anytime clear is called a subscriber will be resubscribed. The new public api method will be store.getRefreshing(barcode) a call to store.clear() drives the refresh

We also need to add clearAll(barcode) which will clear both memory and disk cache.

Why fetch is called every time when getting datas?

I'm using get method, but fetch still get called every time.
I don't know the cache is working or not? 🤔

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "onResume");

    loadPosts();
}
public void loadPosts() {
    Log.d(TAG, "[loadPosts] start");

    BarCode awwRequest = new BarCode(RedditData.class.getSimpleName(), "aww");

    Log.d(TAG, "[loadPosts] Call provideRedditStore get with key \"aww\"");

    provideRedditStore()
            .get(awwRequest)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "[onCompleted]");
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(Integer posts) {
                    Log.d(TAG, "[onNext] get " + posts);
                }
            });
}
private int i = 1;
private Store<Integer, BarCode> provideRedditStore() {
    return StoreBuilder.<Integer>barcode()
            .fetcher(new Fetcher<Integer, BarCode>() {
                @Nonnull
                @Override
                public Observable<Integer> fetch(@Nonnull BarCode barCode) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    int current_i = StoreActivity.this.i++;
                    Log.d(TAG, "[fetch] return " + current_i);
                    return Observable.just(current_i);
                }
            })
            .open();
}

Add Error Prone

The cool kids are using ErrorProne for static analysis and so will we :-)

Expose FileSystem in SourcePersisterFactory

Currently SourcePersisterFactory.create expects a File. We should have an additional override which takes a FileSystem this way you will be able to have a reference to your FileSystemImpl to delete disk cache.

Question: Parsing From API which returns List<T>

Thanks for open sourcing this solution!

Had question about how you typically handle an API which returns a List and parsing it. I'm currently doing:

final Store<List<FooItem>> store = ParsingStoreBuilder.<BufferedSource, List<FooItem>>builder()
          .fetcher(barCode -> api
              .getFooItems()
              .map(ResponseBody::source))
          .persister(persister)
          .parser(source -> {
            try (InputStreamReader reader = new InputStreamReader(source.inputStream())) {
              return gson.fromJson(reader, new TypeToken<List<FooItem>>() {}.getType());
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
          })
          .open();

There is really nothing wrong with this and everything works as expected. Maybe grounds for an enhancement to the middleware down the road unless I'm missing something obvious?

Clarifying Store.stream

Currently I find the implementation of stream(barcode) very confusing.

If I understand correctly, it makes a call with the barcode and then returns all results of all barcodes.
But before reading the documentation I thought that it would stream everything that matches to the barcode.

My suggestion is to remove the barcode from the signature of stream. And to make stream() completely passive (like the method implicates to me).

If someone wants the behavior of what it does currently, he could just use RxJava to archieve exactly that, i.e. Observable.conat(store.get(barcode), store.stream()).

GsonAdaptersModel missing?

I've cloned the Store repository and when I do a build the symbolcom.nytimes.android.sample.data.model.GsonAdaptersModelcannot be resolved. I don't see the source for that class in my workspace and I don't see it in the repository.

Any insights on this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.