Switch OkHttpImagesPlugin to be Call.Factory-based

This is a binary-compatible change that changes the underlying semantics to use a Call.Factory rather than OkHttpClient directly. This allows for a few benefits:

- Not tightly coupled to OkHttpClient
- Allows for lazy/delegating/deferred initialization
- Matches other OkHttpClient-dependent libraries' APIs, namely Retrofit and Apollo GraphQL
This commit is contained in:
Zac Sweers 2019-06-04 01:40:18 -05:00 committed by Dimitry Ivanov
parent 08507c8a92
commit b30a1e10a8
2 changed files with 16 additions and 12 deletions

View File

@ -4,6 +4,7 @@ import android.support.annotation.NonNull;
import java.util.Arrays;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import ru.noties.markwon.AbstractMarkwonPlugin;
import ru.noties.markwon.image.AsyncDrawableLoader;
@ -28,20 +29,25 @@ public class OkHttpImagesPlugin extends AbstractMarkwonPlugin {
@NonNull
public static OkHttpImagesPlugin create(@NonNull OkHttpClient okHttpClient) {
return new OkHttpImagesPlugin(okHttpClient);
return create(okHttpClient);
}
private final OkHttpClient client;
@NonNull
public static OkHttpImagesPlugin create(@NonNull Call.Factory callFactory) {
return new OkHttpImagesPlugin(callFactory);
}
OkHttpImagesPlugin(@NonNull OkHttpClient client) {
this.client = client;
private final Call.Factory callFactory;
OkHttpImagesPlugin(@NonNull Call.Factory callFactory) {
this.callFactory = callFactory;
}
@Override
public void configureImages(@NonNull AsyncDrawableLoader.Builder builder) {
builder.addSchemeHandler(
Arrays.asList(NetworkSchemeHandler.SCHEME_HTTP, NetworkSchemeHandler.SCHEME_HTTPS),
new OkHttpSchemeHandler(client)
new OkHttpSchemeHandler(callFactory)
);
}

View File

@ -3,11 +3,9 @@ package ru.noties.markwon.image.okhttp;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.OkHttpClient;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
@ -18,10 +16,10 @@ class OkHttpSchemeHandler extends SchemeHandler {
private static final String HEADER_CONTENT_TYPE = "Content-Type";
private final OkHttpClient client;
private final Call.Factory callFactory;
OkHttpSchemeHandler(@NonNull OkHttpClient client) {
this.client = client;
OkHttpSchemeHandler(@NonNull Call.Factory callFactory) {
this.callFactory = callFactory;
}
@Nullable
@ -36,7 +34,7 @@ class OkHttpSchemeHandler extends SchemeHandler {
Response response = null;
try {
response = client.newCall(request).execute();
response = callFactory.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}