Skip to content

Commit

Permalink
Simplify service subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
hannobraun committed Apr 26, 2023
1 parent f0b2008 commit e14393c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 37 deletions.
10 changes: 7 additions & 3 deletions crates/fj-kernel/src/services/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,9 @@ pub struct Services {
impl Services {
/// Construct an instance of `Services`
pub fn new() -> Self {
let mut objects = Service::<Objects>::default();
let objects = Service::<Objects>::default();
let validation = Arc::new(Mutex::new(Service::default()));

objects.subscribe(validation.clone());

Self {
objects,
validation,
Expand All @@ -50,6 +48,12 @@ impl Services {
let mut object_events = Vec::new();
self.objects
.execute(Operation::InsertObject { object }, &mut object_events);

for object_event in object_events {
self.validation
.lock()
.execute(object_event, &mut Vec::new());
}
}
}

Expand Down
36 changes: 2 additions & 34 deletions crates/fj-kernel/src/services/service.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use std::{ops::Deref, sync::Arc};

use parking_lot::Mutex;
use std::ops::Deref;

/// A service that controls access to some state
///
Expand All @@ -23,24 +21,12 @@ use parking_lot::Mutex;
/// <https://thinkbeforecoding.com/post/2021/12/17/functional-event-sourcing-decider>
pub struct Service<S: State> {
state: S,
subscribers: Vec<Arc<Mutex<dyn Subscriber<S::Event>>>>,
}

impl<S: State> Service<S> {
/// Create an instance of `Service`
pub fn new(state: S) -> Self {
Self {
state,
subscribers: Vec::new(),
}
}

/// Add a subscriber
pub fn subscribe(
&mut self,
subscriber: Arc<Mutex<dyn Subscriber<S::Event>>>,
) {
self.subscribers.push(subscriber);
Self { state }
}

/// Execute a command
Expand All @@ -52,11 +38,6 @@ impl<S: State> Service<S> {

for event in events {
self.state.evolve(event);

for subscriber in &self.subscribers {
let mut subscriber = subscriber.lock();
subscriber.handle_event(event);
}
}
}

Expand Down Expand Up @@ -90,15 +71,6 @@ where
}
}

impl<S: State> Subscriber<S::Command> for Service<S>
where
S::Command: Clone,
{
fn handle_event(&mut self, event: &S::Command) {
self.execute(event.clone(), &mut Vec::new());
}
}

/// Implemented for state that can be wrapped by a [`Service`]
///
/// See [`Service`] for a detailed explanation.
Expand Down Expand Up @@ -130,7 +102,3 @@ pub trait State {
/// [`State::decide`], and encoded into the event.
fn evolve(&mut self, event: &Self::Event);
}

pub trait Subscriber<T> {
fn handle_event(&mut self, event: &T);
}

0 comments on commit e14393c

Please sign in to comment.