Skip to content

Commit

Permalink
Rename methods and loosen mutability for component link and agent (ye…
Browse files Browse the repository at this point in the history
…wstack#780)

* Rename methods and loosen mutability for component link and agent

* Update send_back to callback

* mut link -> link
  • Loading branch information
jstarry authored and llebout committed Jan 20, 2020
1 parent 42f2e00 commit 3565288
Show file tree
Hide file tree
Showing 19 changed files with 56 additions and 60 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ impl Agent for Worker {
Worker { link }
}

// Handle inner messages (of services of `send_back` callbacks)
// Handle inner messages (from callbacks)
fn update(&mut self, msg: Self::Message) { /* ... */ }

// Handle incoming messages from components of other agents.
Expand Down Expand Up @@ -195,7 +195,7 @@ impl Component for Model {
type Properties = ();

fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let callback = link.send_back(|_| Msg::ContextMsg);
let callback = link.callback(|_| Msg::ContextMsg);
// `Worker::bridge` spawns an instance if no one is available
let context = context::Worker::bridge(callback); // Connected! :tada:
Model { context }
Expand Down Expand Up @@ -362,7 +362,7 @@ impl Component for Model {
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Fire => {
let send_msg = self.link.send_back(|_| Msg::Timeout);
let send_msg = self.link.callback(|_| Msg::Timeout);
self.timeout.spawn(Duration::from_secs(5), send_msg);
}
Msg::Timeout => {
Expand Down
8 changes: 4 additions & 4 deletions examples/dashboard/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl Component for Model {
self.fetching = true;
let task = match format {
Format::Json => {
let callback = self.link.send_back(
let callback = self.link.callback(
move |response: Response<Json<Result<DataFromFile, Error>>>| {
let (meta, Json(data)) = response.into_parts();
println!("META: {:?}, {:?}", meta, data);
Expand All @@ -106,7 +106,7 @@ impl Component for Model {
}
}
Format::Toml => {
let callback = self.link.send_back(
let callback = self.link.callback(
move |response: Response<Toml<Result<DataFromFile, Error>>>| {
let (meta, Toml(data)) = response.into_parts();
println!("META: {:?}, {:?}", meta, data);
Expand All @@ -129,8 +129,8 @@ impl Component for Model {
}
Msg::WsAction(action) => match action {
WsAction::Connect => {
let callback = self.link.send_back(|Json(data)| Msg::WsReady(data));
let notification = self.link.send_back(|status| match status {
let callback = self.link.callback(|Json(data)| Msg::WsReady(data));
let notification = self.link.callback(|status| match status {
WebSocketStatus::Opened => Msg::Ignore,
WebSocketStatus::Closed | WebSocketStatus::Error => WsAction::Lost.into(),
});
Expand Down
4 changes: 2 additions & 2 deletions examples/file_upload/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ impl Component for Model {
for file in files.into_iter() {
let task = {
if chunks {
let callback = self.link.send_back(Msg::Chunk);
let callback = self.link.callback(Msg::Chunk);
self.reader.read_file_by_chunks(file, callback, 10)
} else {
let callback = self.link.send_back(Msg::Loaded);
let callback = self.link.callback(Msg::Loaded);
self.reader.read_file(file, callback)
}
};
Expand Down
2 changes: 1 addition & 1 deletion examples/futures/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl Component for Model {
};
self.link.send_future(future);
self.link
.send_self(SetMarkdownFetchState(FetchState::Fetching));
.send_message(SetMarkdownFetchState(FetchState::Fetching));
false
}
}
Expand Down
4 changes: 2 additions & 2 deletions examples/game_of_life/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,8 @@ impl Component for Model {
type Message = Msg;
type Properties = ();

fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {
let callback = link.send_back(|_| Msg::Tick);
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);
Model {
Expand Down
2 changes: 1 addition & 1 deletion examples/js_callback/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl Component for Model {
}
}
AsyncPayload => {
get_payload_later(self.link.send_back(Msg::Payload));
get_payload_later(self.link.callback(Msg::Payload));
false
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/multi_thread/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl Agent for Worker {
fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3);
let callback = link.send_back(|_| Msg::Updating);
let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback);
Worker {
link,
Expand Down
2 changes: 1 addition & 1 deletion examples/multi_thread/src/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl Agent for Worker {
fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3);
let callback = link.send_back(|_| Msg::Updating);
let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback);
Worker {
link,
Expand Down
10 changes: 5 additions & 5 deletions examples/multi_thread/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@ impl Component for Model {
type Message = Msg;
type Properties = ();

fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {
let callback = link.send_back(|_| Msg::DataReceived);
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let callback = link.callback(|_| Msg::DataReceived);
let worker = native_worker::Worker::bridge(callback);

let callback = link.send_back(|_| Msg::DataReceived);
let callback = link.callback(|_| Msg::DataReceived);
let job = job::Worker::bridge(callback);

let callback = link.send_back(|_| Msg::DataReceived);
let callback = link.callback(|_| Msg::DataReceived);
let context = context::Worker::bridge(callback);

let callback = link.send_back(|_| Msg::DataReceived);
let callback = link.callback(|_| Msg::DataReceived);
let context_2 = context::Worker::bridge(callback);

Model {
Expand Down
2 changes: 1 addition & 1 deletion examples/multi_thread/src/native_worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl Agent for Worker {
fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3);
let callback = link.send_back(|_| Msg::Updating);
let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback);
Worker {
link,
Expand Down
4 changes: 2 additions & 2 deletions examples/npm_and_rest/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ impl Component for Model {
type Message = Msg;
type Properties = ();

fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model {
gravatar: GravatarService::new(),
ccxt: CcxtService::new(),
callback: link.send_back(Msg::GravatarReady),
callback: link.callback(Msg::GravatarReady),
profile: None,
exchanges: Vec::new(),
task: None,
Expand Down
4 changes: 2 additions & 2 deletions examples/routing/src/b_component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ impl Component for BModel {
type Message = Msg;
type Properties = ();

fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {
let callback = link.send_back(|route: Route<()>| Msg::HandleRoute(route));
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let callback = link.callback(|route: Route<()>| Msg::HandleRoute(route));
let mut router = Router::bridge(callback);

router.send(Request::GetCurrentRoute);
Expand Down
4 changes: 2 additions & 2 deletions examples/routing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ impl Component for Model {
type Message = Msg;
type Properties = ();

fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {
let callback = link.send_back(|route: Route<()>| Msg::HandleRoute(route));
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let callback = link.callback(|route: Route<()>| Msg::HandleRoute(route));
let router = router::Router::bridge(callback);
Model {
child: Child::Loading, // This should be quickly overwritten by the actual route.
Expand Down
2 changes: 1 addition & 1 deletion examples/routing/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ where
type Output = Route<T>;

fn create(link: AgentLink<Self>) -> Self {
let callback = link.send_back(|route_changed: (String, T)| {
let callback = link.callback(|route_changed: (String, T)| {
Msg::BrowserNavigationRouteChanged(route_changed)
});
let mut route_service = RouteService::new();
Expand Down
6 changes: 3 additions & 3 deletions examples/timer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl Component for Model {
type Message = Msg;
type Properties = ();

fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
// This callback doesn't send any message to a scope
let callback = |_| {
println!("Example of a standalone callback.");
Expand All @@ -39,8 +39,8 @@ impl Component for Model {
timeout: TimeoutService::new(),
interval,
console: ConsoleService::new(),
callback_tick: link.send_back(|_| Msg::Tick),
callback_done: link.send_back(|_| Msg::Done),
callback_tick: link.callback(|_| Msg::Tick),
callback_done: link.callback(|_| Msg::Done),
job: None,
messages: Vec::new(),
_standalone: Box::new(handle),
Expand Down
9 changes: 4 additions & 5 deletions src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -786,21 +786,20 @@ impl<AGN: Agent> AgentLink<AGN> {
}
}

/// Send response to an actor.
/// Send response to an agent.
pub fn response(&self, id: HandlerId, output: AGN::Output) {
self.responder.response(id, output);
}

/// This method sends messages back to the component's loop.
pub fn send_back<F, IN>(&self, function: F) -> Callback<IN>
/// Create a callback which will send a message to the agent when invoked.
pub fn callback<F, IN>(&self, function: F) -> Callback<IN>
where
F: Fn(IN) -> AGN::Message + 'static,
{
let scope = self.scope.clone();
let closure = move |input| {
let output = function(input);
let msg = AgentUpdate::Message(output);
scope.clone().send(msg);
scope.send(AgentUpdate::Message(output));
};
closure.into()
}
Expand Down
27 changes: 12 additions & 15 deletions src/html/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,9 +385,9 @@ where
}
}

/// This method sends batch of messages back to the component's loop when the
/// returned callback is called.
pub fn send_back_batch<F, IN>(&mut self, function: F) -> Callback<IN>
/// This method creates a `Callback` which will send a batch of messages back to the linked
/// component's update method when called.
pub fn batch_callback<F, IN>(&self, function: F) -> Callback<IN>
where
F: Fn(IN) -> Vec<COMP::Message> + 'static,
{
Expand All @@ -399,15 +399,16 @@ where
closure.into()
}

/// This method sends messages back to the component's loop when the returned callback is called.
pub fn send_back<F, IN>(&mut self, function: F) -> Callback<IN>
/// This method creates a `Callback` which will send a message to the linked component's
/// update method when invoked.
pub fn callback<F, IN>(&self, function: F) -> Callback<IN>
where
F: Fn(IN) -> COMP::Message + 'static,
{
let scope = self.scope.clone();
let closure = move |input| {
let output = function(input);
scope.clone().send_message(output);
scope.send_message(output);
};
closure.into()
}
Expand All @@ -425,21 +426,17 @@ where
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::future_to_promise;

let mut scope = self.scope.clone();

let js_future = async {
let message: COMP::Message = future.await;
// Force movement of the cloned scope into the async block.
let scope_send = move || scope.send_message(message);
scope_send();
let scope = self.scope.clone();
let js_future = async move {
scope.send_message(future.await);
Ok(JsValue::NULL)
};
future_to_promise(js_future);
}

/// This method sends a message to this component to be processed immediately after the
/// component has been updated and/or rendered.
pub fn send_self(&mut self, msg: COMP::Message) {
pub fn send_message(&mut self, msg: COMP::Message) {
self.scope.send_message(msg);
}

Expand All @@ -448,7 +445,7 @@ where
///
/// All messages will first be processed by `update`, and if _any_ of them return `true`,
/// then re-render will occur.
pub fn send_self_batch(&mut self, msgs: Vec<COMP::Message>) {
pub fn send_message_batch(&mut self, msgs: Vec<COMP::Message>) {
self.scope.send_message_batch(msgs)
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/html/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl<COMP: Component> Scope<COMP> {
}

/// Schedules a task to send a message or new props to a component
pub(crate) fn update(&mut self, update: ComponentUpdate<COMP>) {
pub(crate) fn update(&self, update: ComponentUpdate<COMP>) {
let update = UpdateComponent {
shared_state: self.shared_state.clone(),
update,
Expand All @@ -106,12 +106,12 @@ impl<COMP: Component> Scope<COMP> {
}

/// Send a message to the component
pub fn send_message(&mut self, msg: COMP::Message) {
pub fn send_message(&self, msg: COMP::Message) {
self.update(ComponentUpdate::Message(msg));
}

/// Send a batch of messages to the component
pub fn send_message_batch(&mut self, messages: Vec<COMP::Message>) {
pub fn send_message_batch(&self, messages: Vec<COMP::Message>) {
self.update(ComponentUpdate::MessageBatch(messages));
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/services/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,12 @@ impl FetchService {
///# Error
///# }
///# fn dont_execute() {
///# let mut link: ComponentLink<Comp> = unimplemented!();
///# let link: ComponentLink<Comp> = unimplemented!();
///# let mut fetch_service: FetchService = FetchService::new();
///# let post_request: Request<Result<String, failure::Error>> = unimplemented!();
/// let task = fetch_service.fetch(
/// post_request,
/// link.send_back(|response: Response<Result<String, failure::Error>>| {
/// link.callback(|response: Response<Result<String, failure::Error>>| {
/// if response.status().is_success() {
/// Msg::Noop
/// } else {
Expand Down Expand Up @@ -199,9 +199,9 @@ impl FetchService {
/// }
///
///# fn dont_execute() {
///# let mut link: ComponentLink<Comp> = unimplemented!();
///# let link: ComponentLink<Comp> = unimplemented!();
/// let get_request = Request::get("/thing").body(Nothing).unwrap();
/// let callback = link.send_back(|response: Response<Json<Result<Data, failure::Error>>>| {
/// let callback = link.callback(|response: Response<Json<Result<Data, failure::Error>>>| {
/// if let (meta, Json(Ok(body))) = response.into_parts() {
/// if meta.status.is_success() {
/// return Msg::FetchResourceComplete(body);
Expand Down Expand Up @@ -244,8 +244,8 @@ impl FetchService {
///# }
///# pub enum Msg {}
///# fn dont_execute() {
///# let mut link: ComponentLink<Comp> = unimplemented!();
///# let callback = link.send_back(|response: Response<Result<String, failure::Error>>| unimplemented!());
///# let link: ComponentLink<Comp> = unimplemented!();
///# let callback = link.callback(|response: Response<Result<String, failure::Error>>| unimplemented!());
/// let request = fetch::Request::get("/path/")
/// .body(Nothing)
/// .unwrap();
Expand Down

0 comments on commit 3565288

Please sign in to comment.