rok_ui_bloc/lib.rs
1//! The BLoC primitives behind `rok_ui::bloc`, without GPUI.
2//!
3//! A **bloc** turns events into states; a **cubit** exposes methods that emit states. Both keep
4//! their state in an [`Emitter`], which notifies subscribers only when the state changes.
5//! Handlers run on a tokio runtime (in rok-ui apps, `rok_ui::runtime`), and every handler is
6//! cancelled when its bloc closes.
7//!
8//! ```
9//! use rok_ui_bloc::{Bloc, BlocHandle, Emitter};
10//!
11//! #[derive(Clone, Debug, PartialEq)]
12//! struct Count(u32);
13//!
14//! #[derive(Debug)]
15//! enum CounterEvent {
16//! Incremented,
17//! }
18//!
19//! struct CounterBloc;
20//!
21//! impl Bloc for CounterBloc {
22//! type Event = CounterEvent;
23//! type State = Count;
24//!
25//! fn initial_state(&self) -> Count {
26//! Count(0)
27//! }
28//!
29//! async fn on(&self, event: CounterEvent, emit: &Emitter<Count>) {
30//! match event {
31//! CounterEvent::Incremented => {
32//! emit.update(|count| count.0 += 1);
33//! }
34//! }
35//! }
36//! }
37//!
38//! let states = rok_ui_bloc::test::run(CounterBloc, [CounterEvent::Incremented, CounterEvent::Incremented]);
39//! assert_eq!(states, [Count(1), Count(2)]);
40//! ```
41
42mod bloc;
43mod cubit;
44mod emitter;
45mod observer;
46pub mod test;
47
48pub use bloc::{Bloc, BlocHandle, Concurrency};
49
50/// A boxed, sendable future: what repository traits return, since `async fn` in a trait used
51/// as `dyn Trait` is not object-safe.
52///
53/// ```
54/// use rok_ui_bloc::BoxFuture;
55///
56/// trait Clock: Send + Sync {
57/// fn now(&self) -> BoxFuture<'_, u64>;
58/// }
59///
60/// struct Fixed;
61///
62/// impl Clock for Fixed {
63/// fn now(&self) -> BoxFuture<'_, u64> {
64/// Box::pin(async { 42 })
65/// }
66/// }
67/// ```
68pub type BoxFuture<'a, T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;
69pub use cubit::{Cubit, CubitHandle};
70pub use emitter::{Emitter, Observable, Subscription};
71pub use observer::{clear_observer, set_observer, BlocObserver, LogObserver};