question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

NetworkBoundResource: Forcing data fetch from network

See original GitHub issue

I use the approach recommended in Android Architechture Guide and use NetworkBoundResource in my repository. I have SwipeRefreshLayout in my Fragments and I want to implement swipe-to-refresh action for my data in the following way:

  • Force data fetch from the network regardless of the lifetime of my cache
  • If fetch is successful, update cache and show data
  • If fetch is unsuccessful, show previously cached data

I implements methods to get data in my repository in the following way:

public LiveData<Resource<List<Address>>> getAddresses() {
        return new NetworkBoundResource<List<Address>, AddressResponse>(appExecutors) {
            @Override
            protected void saveCallResult(@NonNull AddressResponse response) {
                database.runInTransaction(() -> {
                    addressesDao.deleteAll();
                    addressesDao.insert(response.items);
                });
            }

            @Override
            protected boolean shouldFetch(@Nullable List<Address> data) {
                // isAddressesCacheUpToDate() checks the lifetime of cached data
                return data == null || data.isEmpty() || !isAddressesCacheUpToDate(data);
            }

            @NonNull
            @Override
            protected LiveData<List<Address>> loadFromDb() {
                return addressesDao.get();
            }

            @NonNull
            @Override
            protected LiveData<ApiResponse<AddressResponse>> createCall() {
                return serviceApi.getAddresses();
            }
        }.asLiveData();
    }

I can’t realize how to modify NetworkBoundResource or my repository to implement such forced network fetches. Are there any good solutions for this task?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:9
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

8reactions
santalucommented, Jun 25, 2018

Why not just do this

  public LiveData<Resource<List<Address>>> getAddresses(boolean forceRefresh) {
    return new NetworkBoundResource<List<Address>, AddressResponse>(appExecutors) {
      @Override
      protected void saveCallResult(@NonNull AddressResponse response) {
        database.runInTransaction(() -> {
          addressesDao.deleteAll();
          addressesDao.insert(response.items);
        });
      }

      @Override
      protected boolean shouldFetch(@Nullable List<Address> data) {
        // isAddressesCacheUpToDate() checks the lifetime of cached data
        return forceRefresh || data == null || data.isEmpty() || !isAddressesCacheUpToDate(data);
      }

      @NonNull
      @Override
      protected LiveData<List<Address>> loadFromDb() {
        return addressesDao.get();
      }

      @NonNull
      @Override
      protected LiveData<ApiResponse<AddressResponse>> createCall() {
        return serviceApi.getAddresses();
      }
    }.asLiveData();
  }
1reaction
ianhanniballakecommented, Feb 19, 2020

Consider look at Store, which seeks to cover the repository pattern, encapsulating the loading logic and specifically has support for busting through your local cache.

Read more comments on GitHub >

github_iconTop Results From Across the Web

NetworkBoundResource with RxJava - Medium
It states to first fetch the data from local database; if the data doesn't match a certain condition, then make the required network...
Read more >
Kotlin flow network bound resource usage with force refresh ...
I've made a separate function which reuses fetch and saveFetchResult implementations to put data from network into DB, but I need to refresh...
Read more >
Page from network and database - Android Developers
Cached data is up-to-date, so there is no need to re-fetch ... Any PREPEND or APPEND load requests are forced to wait for...
Read more >
Build an app with offline support: exposing network states
Based on the result from the database, it checks if it is needed to fetch data from the server (the shouldFetch method).
Read more >
how to force to fetch Data from Network before cache
I am using a User Object with Auth uid key, to store user Extra data. The FireBase Persistence is enabled. When I start...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found