1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use crate::prelude::*;

#[derive(Clone)]
pub struct ObserverN<N> {
  next: N,
  is_stopped: bool,
}

impl<Item, N> Observer<Item, ()> for ObserverN<N>
where
  N: FnMut(Item),
{
  #[inline]
  fn next(&mut self, value: Item) { (self.next)(value); }
  #[inline]
  fn error(&mut self, _err: ()) { self.is_stopped = true; }
  #[inline]
  fn complete(&mut self) { self.is_stopped = true; }
  fn is_stopped(&self) -> bool { self.is_stopped }
}

pub trait SubscribeNext<'a, N> {
  /// A type implementing [`SubscriptionLike`]
  type Unsub: SubscriptionLike;

  /// Invokes an execution of an Observable and registers Observer handlers for
  /// notifications it will emit.
  fn subscribe(self, next: N) -> SubscriptionWrapper<Self::Unsub>;
}

impl<'a, S, N> SubscribeNext<'a, N> for S
where
  S: LocalObservable<'a, Err = ()>,
  N: FnMut(S::Item) + 'a,
{
  type Unsub = S::Unsub;
  fn subscribe(self, next: N) -> SubscriptionWrapper<Self::Unsub> {
    let unsub = self.actual_subscribe(Subscriber::local(ObserverN {
      next,
      is_stopped: false,
    }));
    SubscriptionWrapper(unsub)
  }
}

impl<'a, S, N> SubscribeNext<'a, N> for Shared<S>
where
  S: SharedObservable<Err = ()>,
  N: FnMut(S::Item) + Send + Sync + 'static,
{
  type Unsub = S::Unsub;
  fn subscribe(self, next: N) -> SubscriptionWrapper<Self::Unsub> {
    let unsub = self.0.actual_subscribe(Subscriber::shared(ObserverN {
      next,
      is_stopped: false,
    }));
    SubscriptionWrapper(unsub)
  }
}

#[test]
fn raii() {
  let mut times = 0;
  {
    let mut subject = Subject::new();
    {
      let _ = subject
        .clone()
        .subscribe(|_| {
          times += 1;
        })
        .unsubscribe_when_dropped();
    } // <-- guard is dropped here!
    subject.next(());
  }
  assert_eq!(times, 0);
}