Crate reqwest_cross

source ·
Expand description

§reqwest-cross

The reqwest-cross crate (inspired by ehttp) provides a wrapper around reqwest for ease of use in applications that target BOTH native and wasm and do not want to block in the calling task/thread, for example in a UI task/thread. This is achieved by using callbacks and while not ideal a better solution hasn’t been found yet. NOTE: At least 1 feature flag MUST be set to choose which runtime to use for native. To communicate between the callback and the caller you can use various approaches such as channels (used in examples), Arc<Mutex<_>>, promises and so on. egui has an example of how to handle the callback (using promises and their repaint request to wake the UI) here. Their example uses ehttp instead of reqwest-cross but the callback handling can be done the same way. Only real difference in client code is a reqwest::Client, which requires a runtime, is passed instead of a ehttp::Request.

§Examples

For examples of how to use this crate see fetch and the tests.

§Feature Flags

Exactly 1 of the “native-*” flags MUST be enabled to select which runtime to use for native. If one of the other options needs to be used instead of tokio then defaults must be disabled. For example: reqwest-cross = { version = "*", default-features = false, features = ["native-async-std"] } (The feature in this example does not exist at this time, only used for demonstration purposes).

  • native-tokio: Sets tokio as the runtime to use for native. (Default)

§Tradeoffs

Exposing underlying framework that actually sends the requests: The currently selected approach of exposing and using reqwest::RequestBuilder is much more flexible than the fully isolated approach used by ehttp and is generally desirable as it allows for reuse of the same reqwest::Client as recommended by reqwest.However, since reqwest::Client is asynchronous it requires an available runtime. For wasm the spawning of the futures is handled by wasm-bindgen-futures but for local which runtime is specified using feature flags. If the one you want is not listed please create an issue and I’ll attempt to add it.

§How to run tokio on “secondary” thread

If you want to use the main thread for your UI and need to run tokio on a “secondary” thread I found this example helpful. I found it in this discussion, which had other suggested examples as well.

Functions§

  • Performs a HTTP requests and calls the given callback when done. NB: Needs to use a callback to prevent blocking on the thread that initiates the fetch. Note: Instead of calling get like in the example you can use post, put, etc. (See reqwest::Client).