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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use crate::internals::{function_wrapper::*, stream_controller::*};
use crate::prelude::*;

#[derive(Clone)]
pub struct FlatMap<'a, In, Out>
where
  In: Clone + Send + Sync,
  Out: Clone + Send + Sync,
{
  flatmap_f: FunctionWrapper<'a, In, Observable<'a, Out>>,
}

impl<'a, In, Out> FlatMap<'a, In, Out>
where
  In: Clone + Send + Sync + 'a,
  Out: Clone + Send + Sync + 'a,
{
  pub fn new<F>(f: F) -> FlatMap<'a, In, Out>
  where
    F: Fn(In) -> Observable<'a, Out> + Send + Sync + 'a,
  {
    FlatMap { flatmap_f: FunctionWrapper::new(f) }
  }
  pub fn execute(&self, source: Observable<'a, In>) -> Observable<'a, Out> {
    let f = self.flatmap_f.clone();

    Observable::create(move |s| {
      let f = f.clone();

      let sctl = StreamController::new(s);
      let sctl_next = sctl.clone();
      let sctl_error = sctl.clone();
      let sctl_complete = sctl.clone();

      source.inner_subscribe(sctl.new_observer(
        move |_, x| {
          let sctl_next_next = sctl_next.clone();
          let sctl_next_error = sctl_next.clone();
          let sctl_next_complete = sctl_next.clone();

          f.call(x).inner_subscribe(sctl_next.new_observer(
            move |_, xx| {
              sctl_next_next.sink_next(xx);
            },
            move |_, ee| {
              sctl_next_error.sink_error(ee);
            },
            move |serial| {
              sctl_next_complete.sink_complete(&serial);
            },
          ));
        },
        move |_, e| {
          sctl_error.sink_error(e);
        },
        move |serial| {
          sctl_complete.sink_complete(&serial);
        },
      ));
    })
  }
}

impl<'a, Item> Observable<'a, Item>
where
  Item: Clone + Send + Sync,
{
  pub fn flat_map<Out, F>(&self, f: F) -> Observable<'a, Out>
  where
    F: Fn(Item) -> Observable<'a, Out> + Send + Sync + 'a,
    Out: Clone + Send + Sync,
  {
    FlatMap::new(f).execute(self.clone())
  }
}

#[cfg(test)]
mod test {
  use crate::prelude::*;
  use std::{thread, time};

  #[test]
  fn basic() {
    let o = Observable::create(|s| {
      for n in 0..10 {
        s.next(n);
      }
      s.complete();
    });

    o.flat_map(|x| observables::just(x * 2)).subscribe(
      print_next_fmt!("{}"),
      print_error!(),
      print_complete!(),
    );
  }

  #[test]
  fn thread() {
    let o = Observable::create(|s| {
      thread::spawn(move || {
        for n in 0..100 {
          if !s.is_subscribed() {
            println!("break!");
            break;
          }
          s.next(n);
          thread::sleep(time::Duration::from_millis(100));
        }
        if s.is_subscribed() {
          s.complete();
        }
      });
    });

    let binding = o.flat_map(|x| observables::just(format!("str {}", x)));
    let sbsc = binding.subscribe(
      print_next_fmt!("{}"),
      print_error!(),
      print_complete!(),
    );
    thread::sleep(time::Duration::from_millis(500));
    sbsc.unsubscribe();
    thread::sleep(time::Duration::from_millis(500));
  }

  #[test]
  fn composite() {
    fn o() -> Observable<'static, i32> {
      Observable::create(|s| {
        thread::spawn(move || {
          for n in 0..100 {
            if !s.is_subscribed() {
              println!("break!");
              break;
            }
            s.next(n);
            thread::sleep(time::Duration::from_millis(100));
          }
          if s.is_subscribed() {
            s.complete();
          }
        });
      })
    }

    let binding = o().flat_map(move |_x| o());
    let sbsc = binding.subscribe(
      print_next_fmt!("{}"),
      print_error!(),
      print_complete!(),
    );
    thread::sleep(time::Duration::from_millis(500));
    sbsc.unsubscribe();
    thread::sleep(time::Duration::from_millis(500));
  }
}