[android] Do not reach native if the HTTPContext was invalidated

Native will get destroyed before the Java HTTPRequest and asynchronous
requests might still get answered.

If the request gets canceled, we now clear the reference to the native
code and it will never reach it.

Lock is needed because OkHTTP replies on its own thread, so we need to
guard the access to the variable we use for checking if the Request was
canceled. In the future we could remove the lock and use Runnable when
we move Android main loop to Looper instead of libuv.

Like the other implementations of HTTPRequest on Mapbox GL Native, the
request is destroyed synchronously on ::cancel().
This commit is contained in:
Thiago Marcos P. Santos
2016-03-04 17:31:51 -03:00
parent 12fa5679ac
commit fe811bd38e
2 changed files with 29 additions and 17 deletions

View File

@@ -40,8 +40,6 @@ public:
private:
void finish();
bool cancelled = false;
std::unique_ptr<Response> response;
const std::shared_ptr<const Response> existingResponse;
@@ -50,7 +48,6 @@ private:
static const int connectionError = 0;
static const int temporaryError = 1;
static const int permanentError = 2;
static const int canceledError = 3;
};
jni::Class<HTTPRequest> HTTPRequest::javaClass;
@@ -97,20 +94,18 @@ HTTPRequest::HTTPRequest(jni::JNIEnv& env, const Resource& resource_, Callback c
}
void HTTPRequest::cancel() {
cancelled = true;
UniqueEnv env = android::AttachEnv();
static auto cancel = javaClass.GetMethod<void ()>(*env, "cancel");
javaRequest->Call(*env, cancel);
delete this;
}
void HTTPRequest::finish() {
if (!cancelled) {
assert(response);
notify(*response);
}
assert(response);
notify(*response);
delete this;
}
@@ -173,9 +168,6 @@ void HTTPRequest::onFailure(jni::JNIEnv& env, int type, jni::String message) {
case temporaryError:
response->error = std::make_unique<Error>(Error::Reason::Server, messageStr);
break;
case canceledError:
response.reset();
break;
default:
response->error = std::make_unique<Error>(Error::Reason::Other, messageStr);
}