1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef CHROME_BROWSER_ANDROID_PROVIDER_BLOCKING_UI_THREAD_ASYNC_REQUEST_H_
6#define CHROME_BROWSER_ANDROID_PROVIDER_BLOCKING_UI_THREAD_ASYNC_REQUEST_H_
7
8#include "base/bind.h"
9#include "base/callback.h"
10#include "base/synchronization/waitable_event.h"
11#include "chrome/browser/android/provider/run_on_ui_thread_blocking.h"
12#include "content/public/browser/browser_thread.h"
13
14// Allows making async requests and blocking the current thread until the
15// response arrives. The request is performed in the UI thread.
16// Users of this class MUST call RequestCompleted when receiving the response.
17// Cannot be called directly from the UI thread.
18class BlockingUIThreadAsyncRequest {
19 public:
20  BlockingUIThreadAsyncRequest();
21
22  // Runs an asynchronous request, blocking the invoking thread until a response
23  // is received. Class users MUST call RequestCompleted when this happens.
24  // Make sure that the response is also delivered to the UI thread.
25  // The request argument can be defined using base::Bind.
26  template <typename Signature>
27  void RunAsyncRequestOnUIThreadBlocking(base::Callback<Signature> request) {
28    DCHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
29
30    // Make the request in the UI thread.
31    request_completed_.Reset();
32    RunOnUIThreadBlocking::Run(
33        base::Bind(
34            &BlockingUIThreadAsyncRequest::RunRequestOnUIThread<Signature>,
35            request));
36
37    // Wait until the request callback invokes Finished.
38    request_completed_.Wait();
39  }
40
41  // Notifies about a finished request.
42  void RequestCompleted();
43
44 private:
45  template <typename Signature>
46  static void RunRequestOnUIThread(base::Callback<Signature> request) {
47    request.Run();
48  }
49
50  base::WaitableEvent request_completed_;
51
52  DISALLOW_COPY_AND_ASSIGN(BlockingUIThreadAsyncRequest);
53};
54
55#endif  // CHROME_BROWSER_ANDROID_PROVIDER_BLOCKING_UI_THREAD_ASYNC_REQUEST_H_
56