Created
January 9, 2018 21:31
-
-
Save andon/ff47fe4ceb1e300d32c3f883d8e5ac20 to your computer and use it in GitHub Desktop.
Implementation of MainReactPackage thats creates a custom NetworkingModule that configures an HTTP cache.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.cachetester; | |
import com.facebook.react.bridge.ModuleSpec; | |
import com.facebook.react.bridge.NativeModule; | |
import com.facebook.react.bridge.ReactApplicationContext; | |
import com.facebook.react.modules.network.NetworkingModule; | |
import com.facebook.react.modules.network.OkHttpClientProvider; | |
import com.facebook.react.shell.MainReactPackage; | |
import java.io.File; | |
import java.lang.reflect.Constructor; | |
import java.util.ArrayList; | |
import java.util.List; | |
import javax.inject.Provider; | |
import okhttp3.Cache; | |
import okhttp3.OkHttpClient; | |
public class MainReactPackageWithHttpCache extends MainReactPackage { | |
@Override | |
public List<ModuleSpec> getNativeModules(ReactApplicationContext context) { | |
List<ModuleSpec> originalNativeModules = super.getNativeModules(context); | |
List<ModuleSpec> customNativeModules = new ArrayList<>(); | |
ModuleSpec customNetworkingModuleSpec = createNetworkingModuleSpecWithHttpCache(context); | |
for (ModuleSpec originalModuleSpec : originalNativeModules) { | |
if (originalModuleSpec.getType().equals(NetworkingModule.class)) { | |
customNativeModules.add(customNetworkingModuleSpec); | |
} else { | |
customNativeModules.add(originalModuleSpec); | |
} | |
} | |
return customNativeModules; | |
} | |
private ModuleSpec createNetworkingModuleSpecWithHttpCache(final ReactApplicationContext context) { | |
return new ModuleSpec(NetworkingModule.class, new Provider<NativeModule>() { | |
@Override | |
public NativeModule get() { | |
try { | |
Constructor constructorWithOkClient = | |
NetworkingModule.class.getDeclaredConstructor( | |
ReactApplicationContext.class, | |
String.class, | |
OkHttpClient.class); | |
constructorWithOkClient.setAccessible(true); | |
return (NetworkingModule) constructorWithOkClient.newInstance( | |
context, | |
null, | |
createOkHttpClientWithCache(context)); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} | |
}); | |
} | |
private OkHttpClient createOkHttpClientWithCache(ReactApplicationContext context) { | |
return OkHttpClientProvider.createClient().newBuilder() | |
.cache(new Cache(new File(context.getCacheDir(), "http-cache"), 50 * 1024 * 1024)) | |
.build(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment