Make methods static. (#1313)

* Make methods static.

* Fix a call.

* Fix examples.

* Fix examples.

* Fix rest of examples.

* Fix yew-functional.

* Fix interval service example.

* Fix webgl example.

* Fix dialogue service example.

* Use `Default` trait instead of `new()` in `npm_and_rest` example.

* Use `Default` trait instead of `new()` in `npm_and_rest` example.

* Remove use of the `Option` algebraic data type.

* Fix clippy warnings.
This commit is contained in:
Teymour Aldridge 2020-06-22 08:32:04 +01:00 committed by GitHub
parent 7e828d5ade
commit e0aec40fe0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 87 additions and 159 deletions

View File

@ -6,7 +6,6 @@ use yew::{html, Component, ComponentLink, Html, ShouldRender};
pub struct Model {
link: ComponentLink<Self>,
console: ConsoleService,
value: i64,
}
@ -20,22 +19,18 @@ impl Component for Model {
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model {
link,
console: ConsoleService::new(),
value: 0,
}
Model { link, value: 0 }
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Increment => {
self.value += 1;
self.console.log("plus one");
ConsoleService::log("plus one");
}
Msg::Decrement => {
self.value -= 1;
self.console.log("minus one");
ConsoleService::log("minus one");
}
}
true

View File

@ -44,7 +44,6 @@ pub enum Scene {
pub struct Model {
link: ComponentLink<Self>,
storage: StorageService,
dialog: DialogService,
database: Database,
scene: Scene,
}
@ -72,7 +71,6 @@ impl Component for Model {
Model {
link,
storage,
dialog: DialogService::new(),
database,
scene: Scene::ClientsList,
}
@ -126,7 +124,7 @@ impl Component for Model {
},
Scene::Settings => match msg {
Msg::Clear => {
let ok = { self.dialog.confirm("Do you really want to clear the data?") };
let ok = { DialogService::confirm("Do you really want to clear the data?") };
if ok {
self.database.clients.clear();
self.storage.remove(KEY);

View File

@ -55,7 +55,6 @@ pub struct WsResponse {
}
pub struct Model {
ws_service: WebSocketService,
link: ComponentLink<Model>,
fetching: bool,
data: Option<u32>,
@ -123,7 +122,6 @@ impl Component for Model {
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model {
ws_service: WebSocketService::new(),
link,
fetching: false,
data: None,
@ -149,10 +147,9 @@ impl Component for Model {
WebSocketStatus::Opened => Msg::Ignore,
WebSocketStatus::Closed | WebSocketStatus::Error => WsAction::Lost.into(),
});
let task = self
.ws_service
.connect("ws://localhost:9001/", callback, notification)
.unwrap();
let task =
WebSocketService::connect("ws://localhost:9001/", callback, notification)
.unwrap();
self.ws = Some(task);
}
WsAction::SendData(binary) => {

View File

@ -156,8 +156,7 @@ impl Component for Model {
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let callback = link.callback(|_| Msg::Tick);
let mut interval = IntervalService::new();
let handle = interval.spawn(Duration::from_millis(200), callback);
let handle = IntervalService::spawn(Duration::from_millis(200), callback);
Model {
link,

View File

@ -33,7 +33,7 @@ impl Agent for Worker {
fn create(link: AgentLink<Self>) -> Self {
let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating);
let task = IntervalService::new().spawn(duration, callback);
let task = IntervalService::spawn(duration, callback);
Worker {
link,
_task: Box::new(task),

View File

@ -35,7 +35,7 @@ impl Agent for Worker {
fn create(link: AgentLink<Self>) -> Self {
let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating);
let task = IntervalService::new().spawn(duration, callback);
let task = IntervalService::spawn(duration, callback);
link.send_message(Msg::Initialized);
Worker {

View File

@ -33,7 +33,7 @@ impl Agent for Worker {
fn create(link: AgentLink<Self>) -> Self {
let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating);
let task = IntervalService::new().spawn(duration, callback);
let task = IntervalService::spawn(duration, callback);
Worker {
link,
_task: Box::new(task),

View File

@ -1,26 +1,27 @@
use js_sys::{Array, Reflect};
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use web_sys::console;
#[derive(Default)]
pub struct CcxtService(Option<&'static JsValue>);
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
pub struct CcxtService(&'static JsValue);
#[wasm_bindgen]
extern "C" {
static ccxt: JsValue;
}
impl CcxtService {
pub fn new() -> Self {
impl Default for CcxtService {
fn default() -> CcxtService {
let lib: &JsValue = &ccxt;
CcxtService(Some(lib))
CcxtService(lib)
}
}
impl CcxtService {
pub fn exchanges(&mut self) -> Vec<String> {
let lib = self.0.as_ref().expect("ccxt library object lost");
let v = {
let exchanges = Reflect::get(lib, &JsValue::from_str("exchanges")).unwrap();
let exchanges = Reflect::get(&self.0, &JsValue::from_str("exchanges")).unwrap();
console::log_1(&exchanges);
exchanges
};

View File

@ -23,10 +23,6 @@ pub struct Entry {
pub struct GravatarService {}
impl GravatarService {
pub fn new() -> Self {
Self {}
}
pub fn profile(&mut self, hash: &str, callback: Callback<Result<Profile, Error>>) -> FetchTask {
let url = format!("https://en.gravatar.com/{}.json", hash);
let handler = move |response: Response<Json<Result<Profile, Error>>>| {

View File

@ -34,8 +34,8 @@ impl Component for Model {
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model {
link: link.clone(),
gravatar: GravatarService::new(),
ccxt: CcxtService::new(),
gravatar: GravatarService::default(),
ccxt: CcxtService::default(),
callback: link.callback(Msg::GravatarReady),
profile: None,
exchanges: Vec::new(),

View File

@ -6,9 +6,6 @@ use yew::{html, Callback, Component, ComponentLink, Html, ShouldRender};
pub struct Model {
link: ComponentLink<Self>,
timeout: TimeoutService,
interval: IntervalService,
console: ConsoleService,
callback_tick: Callback<()>,
callback_done: Callback<()>,
job: Option<Box<dyn Task>>,
@ -33,14 +30,10 @@ impl Component for Model {
let callback = |_| {
println!("Example of a standalone callback.");
};
let mut interval = IntervalService::new();
let handle = interval.spawn(Duration::from_secs(10), callback.into());
let handle = IntervalService::spawn(Duration::from_secs(10), callback.into());
Model {
link: link.clone(),
timeout: TimeoutService::new(),
interval,
console: ConsoleService::new(),
callback_tick: link.callback(|_| Msg::Tick),
callback_done: link.callback(|_| Msg::Done),
job: None,
@ -53,45 +46,43 @@ impl Component for Model {
match msg {
Msg::StartTimeout => {
{
let handle = self
.timeout
.spawn(Duration::from_secs(3), self.callback_done.clone());
let handle =
TimeoutService::spawn(Duration::from_secs(3), self.callback_done.clone());
self.job = Some(Box::new(handle));
}
self.messages.clear();
self.console.clear();
ConsoleService::clear();
self.messages.push("Timer started!");
self.console.time_named("Timer");
ConsoleService::time_named("Timer");
}
Msg::StartInterval => {
{
let handle = self
.interval
.spawn(Duration::from_secs(1), self.callback_tick.clone());
let handle =
IntervalService::spawn(Duration::from_secs(1), self.callback_tick.clone());
self.job = Some(Box::new(handle));
}
self.messages.clear();
self.console.clear();
ConsoleService::clear();
self.messages.push("Interval started!");
self.console.log("Interval started!");
ConsoleService::log("Interval started!");
}
Msg::Cancel => {
self.job.take();
self.messages.push("Canceled!");
self.console.warn("Canceled!");
self.console.assert(self.job.is_none(), "Job still exists!");
ConsoleService::warn("Canceled!");
ConsoleService::assert(self.job.is_none(), "Job still exists!");
}
Msg::Done => {
self.messages.push("Done!");
self.console.group();
self.console.info("Done!");
self.console.time_named_end("Timer");
self.console.group_end();
ConsoleService::group();
ConsoleService::info("Done!");
ConsoleService::time_named_end("Timer");
ConsoleService::group_end();
self.job = None;
}
Msg::Tick => {
self.messages.push("Tick...");
self.console.count_named("Tick");
ConsoleService::count_named("Tick");
}
}
true

View File

@ -55,7 +55,7 @@ impl Component for Model {
// The callback to request animation frame is passed a time value which can be used for
// rendering motion independent of the framerate which may vary.
let render_frame = self.link.callback(Msg::Render);
let handle = RenderService::new().request_animation_frame(render_frame);
let handle = RenderService::request_animation_frame(render_frame);
// A reference to the handle must be stored, otherwise it is dropped and the render won't
// occur.
@ -131,7 +131,7 @@ impl Model {
gl.draw_arrays(GL::TRIANGLES, 0, 6);
let render_frame = self.link.callback(Msg::Render);
let handle = RenderService::new().request_animation_frame(render_frame);
let handle = RenderService::request_animation_frame(render_frame);
// A reference to the new handle must be retained for the next render to run.
self.render_loop = Some(Box::new(handle));

View File

@ -34,7 +34,7 @@ fn use_context_scoping_works() {
fn run(_props: &Self::TProps) -> Html {
if use_context::<ExampleContext>().is_some() {
yew::services::ConsoleService::new().log(&format!(
yew::services::ConsoleService::log(&format!(
"Context should be None here, but was {:?}!",
use_context::<ExampleContext>().unwrap()
));

View File

@ -6,7 +6,6 @@ use yew::{html, Component, ComponentLink, Html, ShouldRender};
pub struct Model {
link: ComponentLink<Self>,
console: ConsoleService,
value: i64,
}
@ -20,22 +19,18 @@ impl Component for Model {
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model {
link,
console: ConsoleService::new(),
value: 0,
}
Model { link, value: 0 }
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Increment => {
self.value += 1;
self.console.log("plus one");
ConsoleService::log("plus one");
}
Msg::Decrement => {
self.value -= 1;
self.console.log("minus one");
ConsoleService::log("minus one");
}
}
true

View File

@ -31,10 +31,9 @@ impl Agent for Worker {
type Output = Response;
fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback);
let task = IntervalService::spawn(duration, callback);
Worker {
link,
_task: Box::new(task),

View File

@ -31,10 +31,9 @@ impl Agent for Worker {
type Output = Response;
fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback);
let task = IntervalService::spawn(duration, callback);
Worker {
link,
_task: Box::new(task),

View File

@ -31,10 +31,9 @@ impl Agent for Worker {
type Output = Response;
fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback);
let task = IntervalService::spawn(duration, callback);
Worker {
link,
_task: Box::new(task),

View File

@ -18,14 +18,10 @@ cfg_if! {
pub struct ConsoleService {}
impl ConsoleService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// [console.log](https://developer.mozilla.org/en-US/docs/Web/API/Console/log)
/// method implementation.
pub fn log(&mut self, message: &str) {
/// This method outputs the provided message to the console.
pub fn log(message: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.log(@{message}); },
feature = "web_sys" => console::log_1(&JsValue::from_str(message)),
@ -34,7 +30,8 @@ impl ConsoleService {
/// [console.warn](https://developer.mozilla.org/en-US/docs/Web/API/Console/warn)
/// method implementation.
pub fn warn(&mut self, message: &str) {
/// This method outputs the provided message to the console as a warning.
pub fn warn(message: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.warn(@{message}); },
feature = "web_sys" => console::warn_1(&JsValue::from_str(message)),
@ -43,7 +40,8 @@ impl ConsoleService {
/// [console.info](https://developer.mozilla.org/en-US/docs/Web/API/Console/info)
/// method implementation.
pub fn info(&mut self, message: &str) {
/// This method outputs the provided message to the console as information.
pub fn info(message: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.info(@{message}); },
feature = "web_sys" => console::info_1(&JsValue::from_str(message)),
@ -52,7 +50,8 @@ impl ConsoleService {
/// [console.error](https://developer.mozilla.org/en-US/docs/Web/API/Console/error)
/// method implementation.
pub fn error(&mut self, message: &str) {
/// This method outputs the provided message to the console as an error.
pub fn error(message: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.error(@{message}); },
feature = "web_sys" => console::error_1(&JsValue::from_str(message)),
@ -61,7 +60,7 @@ impl ConsoleService {
/// [console.debug](https://developer.mozilla.org/en-US/docs/Web/API/Console/debug)
/// method implementation.
pub fn debug(&mut self, message: &str) {
pub fn debug(message: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.debug(@{message}); },
feature = "web_sys" => console::debug_1(&JsValue::from_str(message)),
@ -70,7 +69,7 @@ impl ConsoleService {
/// [console.count_named](https://developer.mozilla.org/en-US/docs/Web/API/Console/count_named)
/// method implementation.
pub fn count_named(&mut self, name: &str) {
pub fn count_named(name: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.count(@{name}); },
feature = "web_sys" => console::count_with_label(name),
@ -79,7 +78,7 @@ impl ConsoleService {
/// [console.count](https://developer.mozilla.org/en-US/docs/Web/API/Console/count)
/// method implementation.
pub fn count(&mut self) {
pub fn count() {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.count(); },
feature = "web_sys" => console::count(),
@ -88,7 +87,7 @@ impl ConsoleService {
/// [console.time_named](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_named)
/// method implementation.
pub fn time_named(&mut self, name: &str) {
pub fn time_named(name: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.time(@{name}); },
feature = "web_sys" => console::time_with_label(name),
@ -97,7 +96,7 @@ impl ConsoleService {
/// [console.time_named_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_named_end)
/// method implementation.
pub fn time_named_end(&mut self, name: &str) {
pub fn time_named_end(name: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.timeEnd(@{name}); },
feature = "web_sys" => console::time_end_with_label(name),
@ -106,7 +105,7 @@ impl ConsoleService {
/// [console.time](https://developer.mozilla.org/en-US/docs/Web/API/Console/time)
/// method implementation.
pub fn time(&mut self) {
pub fn time() {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.time(); },
feature = "web_sys" => console::time(),
@ -114,7 +113,7 @@ impl ConsoleService {
}
/// [console.time_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_end)
/// method implementation.
pub fn time_end(&mut self) {
pub fn time_end() {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.timeEnd(); },
feature = "web_sys" => console::time_end(),
@ -123,7 +122,7 @@ impl ConsoleService {
/// [console.clear](https://developer.mozilla.org/en-US/docs/Web/API/Console/clear)
/// method implementation.
pub fn clear(&mut self) {
pub fn clear() {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.clear(); },
feature = "web_sys" => console::clear(),
@ -132,7 +131,7 @@ impl ConsoleService {
/// [console.group](https://developer.mozilla.org/en-US/docs/Web/API/Console/group)
/// method implementation.
pub fn group(&mut self) {
pub fn group() {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.group(); },
feature = "web_sys" => console::group_0(),
@ -141,7 +140,7 @@ impl ConsoleService {
/// [console.group_collapsed](https://developer.mozilla.org/en-US/docs/Web/API/Console/group_collapsed)
/// method implementation.
pub fn group_collapsed(&mut self) {
pub fn group_collapsed() {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.groupCollapsed(); },
feature = "web_sys" => console::group_collapsed_0(),
@ -150,7 +149,7 @@ impl ConsoleService {
/// [console.group_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/group_end)
/// method implementation.
pub fn group_end(&mut self) {
pub fn group_end() {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.groupEnd(); },
feature = "web_sys" => console::group_end(),
@ -159,7 +158,8 @@ impl ConsoleService {
/// [console.trace](https://developer.mozilla.org/en-US/docs/Web/API/Console/trace)
/// method implementation.
pub fn trace(&mut self) {
/// This method outputs the current stack trace to the console.
pub fn trace() {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.trace(); },
feature = "web_sys" => console::trace_0(),
@ -168,7 +168,7 @@ impl ConsoleService {
/// [console.assert](https://developer.mozilla.org/en-US/docs/Web/API/Console/assert)
/// method implementation.
pub fn assert(&mut self, condition: bool, message: &str) {
pub fn assert(condition: bool, message: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) console.assert(@{condition}, @{message}); },
feature = "web_sys" => console::assert_with_condition_and_data_1(condition, &String::from(message).into()),

View File

@ -18,14 +18,9 @@ cfg_if! {
pub struct DialogService {}
impl DialogService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Calls [alert](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert)
/// function.
pub fn alert(&mut self, message: &str) {
pub fn alert(message: &str) {
cfg_match! {
feature = "std_web" => js! { @(no_return) alert(@{message}); },
feature = "web_sys" => utils::window().alert_with_message(message).unwrap(),
@ -34,7 +29,7 @@ impl DialogService {
/// Calls [confirm](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
/// function.
pub fn confirm(&mut self, message: &str) -> bool {
pub fn confirm(message: &str) -> bool {
cfg_match! {
feature = "std_web" => ({
let value: Value = js! { return confirm(@{message}); };

View File

@ -161,11 +161,6 @@ impl fmt::Debug for FetchTask {
pub struct FetchService {}
impl FetchService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Sends a request to a remote server given a Request object and a callback
/// function to convert a Response object into a loop's message.
///

View File

@ -163,11 +163,6 @@ impl fmt::Debug for FetchTask {
pub struct FetchService {}
impl FetchService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Sends a request to a remote server given a Request object and a callback
/// fuction to convert a Response object into a loop's message.
///

View File

@ -36,14 +36,9 @@ impl fmt::Debug for IntervalTask {
pub struct IntervalService {}
impl IntervalService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Sets interval which will call send a messages returned by a converter
/// on every intarval expiration.
pub fn spawn(&mut self, duration: Duration, callback: Callback<()>) -> IntervalTask {
pub fn spawn(duration: Duration, callback: Callback<()>) -> IntervalTask {
let callback = move || {
callback.emit(());
};

View File

@ -38,13 +38,14 @@ pub use self::websocket::WebSocketService;
use std::time::Duration;
/// An universal task of a service.
/// It have to be canceled when dropped.
/// The task must be handled when it is cancelled.
pub trait Task: Drop {
/// Returns `true` if task is active.
fn is_active(&self) -> bool;
}
#[doc(hidden)]
/// Converts a `Duration` into milliseconds.
fn to_ms(duration: Duration) -> u32 {
let ms = duration.subsec_millis();
ms + duration.as_secs() as u32 * 1000

View File

@ -44,13 +44,8 @@ impl fmt::Debug for RenderTask {
pub struct RenderService {}
impl RenderService {
/// Create a new instance of the service.
pub fn new() -> Self {
Self {}
}
/// Request animation frame. Callback will be notified when frame should be rendered.
pub fn request_animation_frame(&mut self, callback: Callback<f64>) -> RenderTask {
pub fn request_animation_frame(callback: Callback<f64>) -> RenderTask {
let callback = move |#[cfg(feature = "std_web")] v,
#[cfg(feature = "web_sys")] v: JsValue| {
let time: f64 = cfg_match! {

View File

@ -35,13 +35,8 @@ impl fmt::Debug for TimeoutTask {
pub struct TimeoutService {}
impl TimeoutService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Sets timeout which sends messages from a `converter` after `duration`.
pub fn spawn(&mut self, duration: Duration, callback: Callback<()>) -> TimeoutTask {
pub fn spawn(duration: Duration, callback: Callback<()>) -> TimeoutTask {
let callback = move || {
callback.emit(());
};

View File

@ -69,15 +69,9 @@ impl fmt::Debug for WebSocketTask {
pub struct WebSocketService {}
impl WebSocketService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Connects to a server by a websocket connection. Needs two functions to generate
/// data and notification messages.
pub fn connect<OUT: 'static>(
&mut self,
url: &str,
callback: Callback<OUT>,
notification: Callback<WebSocketStatus>,
@ -87,14 +81,14 @@ impl WebSocketService {
{
cfg_match! {
feature = "std_web" => ({
let ws = self.connect_common(url, &notification)?.0;
let ws = Self::connect_common(url, &notification)?.0;
ws.add_event_listener(move |event: SocketMessageEvent| {
process_both(&event, &callback);
});
Ok(WebSocketTask { ws, notification })
}),
feature = "web_sys" => ({
let ConnectCommon(ws, listeners) = self.connect_common(url, &notification)?;
let ConnectCommon(ws, listeners) = Self::connect_common(url, &notification)?;
let listener = EventListener::new(&ws, "message", move |event: &Event| {
let event = event.dyn_ref::<MessageEvent>().unwrap();
process_both(&event, &callback);
@ -109,7 +103,6 @@ impl WebSocketService {
/// ignored. Needs two functions to generate data and notification
/// messages.
pub fn connect_binary<OUT: 'static>(
&mut self,
url: &str,
callback: Callback<OUT>,
notification: Callback<WebSocketStatus>,
@ -119,14 +112,14 @@ impl WebSocketService {
{
cfg_match! {
feature = "std_web" => ({
let ws = self.connect_common(url, &notification)?.0;
let ws = Self::connect_common(url, &notification)?.0;
ws.add_event_listener(move |event: SocketMessageEvent| {
process_binary(&event, &callback);
});
Ok(WebSocketTask { ws, notification })
}),
feature = "web_sys" => ({
let ConnectCommon(ws, listeners) = self.connect_common(url, &notification)?;
let ConnectCommon(ws, listeners) = Self::connect_common(url, &notification)?;
let listener = EventListener::new(&ws, "message", move |event: &Event| {
let event = event.dyn_ref::<MessageEvent>().unwrap();
process_binary(&event, &callback);
@ -141,7 +134,6 @@ impl WebSocketService {
/// ignored. Needs two functions to generate data and notification
/// messages.
pub fn connect_text<OUT: 'static>(
&mut self,
url: &str,
callback: Callback<OUT>,
notification: Callback<WebSocketStatus>,
@ -151,14 +143,14 @@ impl WebSocketService {
{
cfg_match! {
feature = "std_web" => ({
let ws = self.connect_common(url, &notification)?.0;
let ws = Self::connect_common(url, &notification)?.0;
ws.add_event_listener(move |event: SocketMessageEvent| {
process_text(&event, &callback);
});
Ok(WebSocketTask { ws, notification })
}),
feature = "web_sys" => ({
let ConnectCommon(ws, listeners) = self.connect_common(url, &notification)?;
let ConnectCommon(ws, listeners) = Self::connect_common(url, &notification)?;
let listener = EventListener::new(&ws, "message", move |event: &Event| {
let event = event.dyn_ref::<MessageEvent>().unwrap();
process_text(&event, &callback);
@ -169,10 +161,9 @@ impl WebSocketService {
}
fn connect_common(
&mut self,
url: &str,
notification: &Callback<WebSocketStatus>,
) -> Result<ConnectCommon, &str> {
) -> Result<ConnectCommon, &'static str> {
let ws = WebSocket::new(url);
if ws.is_err() {
return Err("Failed to created websocket with given URL");
@ -379,8 +370,7 @@ mod tests {
let status_future = CallbackFuture::<WebSocketStatus>::default();
let notification: Callback<_> = status_future.clone().into();
let mut ws = WebSocketService::new();
let mut task = ws.connect(url, callback, notification).unwrap();
let mut task = WebSocketService::connect(url, callback, notification).unwrap();
assert_eq!(status_future.await, WebSocketStatus::Opened);
let msg = Message {
@ -408,8 +398,7 @@ mod tests {
let status_future = CallbackFuture::<WebSocketStatus>::default();
let notification: Callback<_> = status_future.clone().into();
let mut ws = WebSocketService::new();
let mut task = ws.connect_text(url, callback, notification).unwrap();
let mut task = WebSocketService::connect_text(url, callback, notification).unwrap();
assert_eq!(status_future.await, WebSocketStatus::Opened);
let msg = Message {
@ -440,8 +429,7 @@ mod tests {
let status_future = CallbackFuture::<WebSocketStatus>::default();
let notification: Callback<_> = status_future.clone().into();
let mut ws = WebSocketService::new();
let mut task = ws.connect_binary(url, callback, notification).unwrap();
let mut task = WebSocketService::connect_binary(url, callback, notification).unwrap();
assert_eq!(status_future.await, WebSocketStatus::Opened);
let msg = Message {