Skip to content

Commit

Permalink
Add back ability to customise OkHttp client
Browse files Browse the repository at this point in the history
Prior to 0a71f48, users could customise
the OkHttp client used by React Native on Android by calling
replaceOkHttpClient in OkHttpClientProvider.

This functionality has a variety of legitimate applications from
changing connection timeouts or pool size to Stetho integration. The
challenge is to add back support for replacing the client without
causing a breaking change or undoing the problems @olegbl sought to
address in his original commit. Introducing a client factory achives
these aims, it adds a new, backwards compatible interface and is called
each time a client is requested rather than re-using the same instance
(unless you explicitly want this behaviour, in which case you could
replicate it using a static class property inside your custom factory).
  • Loading branch information
cdlewis committed Jan 30, 2018
1 parent c7ed03a commit f6ea205
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/

package com.facebook.react.modules.network;

import okhttp3.OkHttpClient;

public interface OkHttpClientFactory {
OkHttpClient createNewNetworkModuleClient();
};
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ public class OkHttpClientProvider {
// Centralized OkHttpClient for all networking requests.
private static @Nullable OkHttpClient sClient;

// User-provided OkHttpClient factory
private static @Nullable OkHttpClientFactory sFactory;

public static void setOkHttpClientFactory(OkHttpClientFactory factory) {
sFactory = factory;
}

public static OkHttpClient getOkHttpClient() {
if (sClient == null) {
sClient = createClient();
Expand All @@ -46,6 +53,10 @@ public static void replaceOkHttpClient(OkHttpClient client) {
}

public static OkHttpClient createClient() {
if (sFactory != null) {
return sFactory.createNewNetworkModuleClient();
}

// No timeouts by default
OkHttpClient.Builder client = new OkHttpClient.Builder()
.connectTimeout(0, TimeUnit.MILLISECONDS)
Expand Down

0 comments on commit f6ea205

Please sign in to comment.