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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
//! The `observable` module provides the building blocks for creating and manipulating
//! observables, allowing for reactive programming in Rust.

#![allow(clippy::needless_doctest_main)]

mod background_unsubscribe;
pub mod multicast;

use std::{
    collections::VecDeque,
    error::Error,
    sync::{Arc, Mutex},
    time::Duration,
};

use crate::{observer::Observer, subscribe::Fuse, subscription::subscribe::UnsubscribeLogic};
use crate::{
    subscribe::SubscriptionCollection,
    subscription::subscribe::{
        Subscribeable, Subscriber, Subscription, SubscriptionHandle, Unsubscribeable,
    },
};

use self::{background_unsubscribe::setup_unsubscribe_channel, multicast::Connectable};

enum EmittedValue<T> {
    Success(T),
    Complete,
    Error(Arc<dyn std::error::Error + Send + Sync>),
}

/// Error indicating that an observable sequence is empty.
#[derive(Debug, Clone)]
pub struct EmptyError;

impl std::fmt::Display for EmptyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "no elements in sequence")
    }
}

impl Error for EmptyError {}

type SubscribeFn<T> = Box<dyn FnMut(Subscriber<T>) -> Subscription + Send + Sync>;
type PendingObservables<T> = VecDeque<(Observable<T>, Subscriber<T>)>;

/// The `Observable` struct represents a source of values that can be observed
/// and transformed.
///
/// This struct serves as the foundation for creating, transforming, and working with
/// observables. It provides methods for applying operators, subscribing to emitted
/// values, and creating new observables.
///
/// # Example: basic synchronous `Observable`
///
/// This simple `Observable` emits values and completes. It returns an empty `Subscription`,
/// making it unable to be unsubscribed from. Some operators like `take`, `switch_map`,
/// `merge_map`, `concat_map`, and `exhaust_map` require unsubscribe functionality to
/// work correctly.
///
/// Additionally, this is a synchronous `Observable`, so it blocks the current thread
/// until it completes emission.
///
/// ```no_run
/// use rxr::subscribe::{Subscriber, Subscription, SubscriptionHandle, UnsubscribeLogic};
/// use rxr::{Observable, Observer, Subscribeable};
///
/// // Create a custom observable that emits values from 1 to 10.
/// let mut emit_10_observable = Observable::new(|mut subscriber| {
///     let mut i = 1;
///
///     while i <= 10 {
///         // Emit the value to the subscriber.
///         subscriber.next(i);
///         i += 1;
///     }
///     // Signal completion to the subscriber.
///     subscriber.complete();
///
///     // Return the empty subscription.
///     Subscription::new(UnsubscribeLogic::Nil, SubscriptionHandle::Nil)
/// });
///
/// // Create the `Subscriber` with a mandatory `next` function, and optional
/// // `complete` function. No need for `error` function in this simple example.
/// let mut observer = Subscriber::on_next(|v| println!("Emitted {}", v));
/// observer.on_complete(|| println!("Completed"));
///
/// // This observable blocks until completion since it doesn't use async or
/// // threads. If you comment out the line below, no emissions will occur
/// // because observables are cold.
/// emit_10_observable.subscribe(observer);
///
/// println!("Custom Observable finished emmiting")
/// ```
///
/// # Example: basic asynchronous `Observable`
///
/// Emits values and completes, returning an empty `Subscription`, making it unable
/// to be unsubscribed from. Some operators like `take`, `switch_map`, `merge_map`,
/// `concat_map`, and `exhaust_map` require unsubscribe functionality to work correctly.
///
/// Utilizes an OS thread for asynchronous processing, preventing it from blocking
/// the current thread.
///
/// ```no_run
/// use std::time::Duration;
///
/// use rxr::{
///     subscribe::{Subscriber, Subscription, SubscriptionHandle, UnsubscribeLogic},
///     Observable, ObservableExt, Observer, Subscribeable,
/// };
///
/// // Create a custom observable that emits values from 1 to 10 in separate thread.
/// let observable = Observable::new(|mut o| {
///     // Launch a new thread for the Observable's processing and store its handle.
///     let join_handle = std::thread::spawn(move || {
///         for i in 0..=15 {
///             // Emit the value to the subscriber.
///             o.next(i);
///             // Important. Put an await point after each emit or after some emits.
///             // This allows the `take()` operator to function properly.
///             // Not required in this example.
///             std::thread::sleep(Duration::from_millis(1));
///         }
///         // Signal completion to the subscriber.
///         o.complete();
///     });
///
///     // Return the subscription.
///     Subscription::new(
///         // In this example, we omit the unsubscribe functionality. Without it, we
///         // can't unsubscribe, which prevents the `take()` operator, as well as
///         // higher-order operators like `switch_map`, `merge_map`, `concat_map`,
///         // and `exhaust_map`, from functioning as expected.
///         UnsubscribeLogic::Nil,
///         // Store the `JoinHandle` to enable waiting functionality using the
///         // `Subscription` for this Observable thread to complete.
///         SubscriptionHandle::JoinThread(join_handle),
///     )
/// });
///
/// // Create the `Subscriber` with a mandatory `next` function, and optional
/// // `complete` function. No need for `error` function in this simple example.
/// let mut observer = Subscriber::on_next(|v| println!("Emitted {}", v));
/// observer.on_complete(|| println!("Completed"));
///
/// // This observable uses OS threads so it will not block the current thread.
/// // Observables are cold so if you comment out the statement bellow nothing
/// // will be emitted.
/// let subscription = observable
///     .filter(|&v| v <= 10)
///     .map(|v| format!("Mapped {}", v))
///     .subscribe(observer);
///
/// // Do something else here.
/// println!("Do something while Observable is emitting.");
///
/// // Because the subscription creates a new thread, we can utilize the `Subscription`
/// // to wait for its completion. This ensures that the main thread won't terminate
/// // prematurely and stop all child threads.
/// if subscription.join().is_err() {
///     // Handle error
/// }
///
/// println!("Custom Observable finished emmiting")
/// ```
///
/// # Example: asynchronous `Observable` with `unsubscribe`
///
/// Emits values and completes, returning a `Subscription` that can be unsubscribed
/// from, enabling all operators to function correctly. Utilizes an OS thread for
/// asynchronous processing, preventing it from blocking the current thread.
///
/// ```no_run
/// use std::{
///     sync::{Arc, Mutex},
///     time::Duration,
/// };
///
/// use rxr::{
///     subscribe::{Subscriber, Subscription, SubscriptionHandle, UnsubscribeLogic, Unsubscribeable},
///     Observable, ObservableExt, Observer, Subscribeable,
/// };
///
/// const UNSUBSCRIBE_SIGNAL: bool = true;
///
/// // Create a custom observable that emits values in a separate thread.
/// let observable = Observable::new(|mut o| {
///     let done = Arc::new(Mutex::new(false));
///     let done_c = Arc::clone(&done);
///     let (tx, rx) = std::sync::mpsc::channel();
///
///     // Spawn a new thread to await a signal sent from the unsubscribe logic.
///     std::thread::spawn(move || {
///         // Attempt to receive a signal sent from the unsubscribe logic.
///         if let Ok(UNSUBSCRIBE_SIGNAL) = rx.recv() {
///             // Update the `done_c` mutex with the received signal.
///             *done_c.lock().unwrap() = UNSUBSCRIBE_SIGNAL;
///         }
///     });
///
///     // Launch a new thread for the Observable's processing and store its handle.
///     let join_handle = std::thread::spawn(move || {
///         for i in 0..=10000 {
///             // If an unsubscribe signal is received, exit the loop and stop emissions.
///             if *done.lock().unwrap() == UNSUBSCRIBE_SIGNAL {
///                 break;
///             }
///             // Emit the value to the subscriber.
///             o.next(i);
///             // Important. Put an await point after each emit or after some emits.
///             // This allows the `take()` operator to function properly.
///             std::thread::sleep(Duration::from_millis(1));
///         }
///         // Signal completion to the subscriber.
///         o.complete();
///     });
///
///     // Return a new `Subscription` with custom unsubscribe logic.
///     Subscription::new(
///         // The provided closure defines the behavior of the subscription when it
///         // is unsubscribed. In this case, it sends a signal to an asynchronous
///         // observable to stop emitting values.
///         UnsubscribeLogic::Logic(Box::new(move || {
///             if tx.send(UNSUBSCRIBE_SIGNAL).is_err() {
///                 println!("Receiver dropped.");
///             }
///         })),
///         // Store the `JoinHandle` for awaiting completion using the `Subscription`.
///         SubscriptionHandle::JoinThread(join_handle),
///     )
/// });
///
/// // Create the `Subscriber` with a mandatory `next` function, and optional
/// // `complete` function. No need for `error` function in this simple example.
/// let mut observer = Subscriber::on_next(|v| println!("Emitted {}", v));
/// observer.on_complete(|| println!("Completed"));
///
/// // This observable uses OS threads so it will not block the current thread.
/// // Observables are cold so if you comment out the statement bellow nothing
/// // will be emitted.
/// let subscription = observable
///     // `take` utilizes our unsubscribe function to stop background emissions
///     // after a specified item count.
///     .take(500)
///     .map(|v| format!("Mapped {}", v))
///     .subscribe(observer);
///
/// // Do something else here.
/// println!("Do something while Observable is emitting.");
///
/// // Unsubscribe from the observable to stop emissions.
/// subscription.unsubscribe();
///
/// // Allow some time for the main thread to confirm that the observable indeed
/// // isn't emitting.
/// std::thread::sleep(Duration::from_millis(2000));
/// println!("`main` function done")
/// ```
///
/// # Example: asynchronous `Observable` with `Tokio`
///
/// Emits values and completes, returning a `Subscription` that can be unsubscribed
/// from, enabling all operators to function correctly. Utilizes `Tokio` tasks for
/// asynchronous processing, preventing it from blocking the current thread.
///
///```no_run
/// use std::sync::{Arc, Mutex};
///
/// use rxr::{
///     subscribe::{Subscriber, Subscription, SubscriptionHandle, UnsubscribeLogic},
///     Observable, ObservableExt, Observer, Subscribeable,
/// };
///
/// use tokio::{task, time, sync::mpsc::channel};
///
/// const UNSUBSCRIBE_SIGNAL: bool = true;
///
/// #[tokio::main()]
/// async fn main() {
///     // Create a custom observable that emits values in a separate task.
///     let observable = Observable::new(|mut o| {
///         let done = Arc::new(Mutex::new(false));
///         let done_c = Arc::clone(&done);
///         let (tx, mut rx) = channel(10);
///
///         // Spawn a new Tokio task to await a signal sent from the unsubscribe logic.
///         task::spawn(async move {
///             // Attempt to receive a signal sent from the unsubscribe logic.
///             if let Some(UNSUBSCRIBE_SIGNAL) = rx.recv().await {
///                 // Update the `done_c` mutex with the received signal.
///                 *done_c.lock().unwrap() = UNSUBSCRIBE_SIGNAL;
///             }
///         });
///
///         // Launch a new Tokio task for the Observable's processing and store its handle.
///         let join_handle = task::spawn(async move {
///             for i in 0..=10000 {
///                 // If an unsubscribe signal is received, exit the loop and stop emissions.
///                 if *done.lock().unwrap() == UNSUBSCRIBE_SIGNAL {
///                     break;
///                 }
///                 // Emit the value to the subscriber.
///                 o.next(i);
///                 // Important. Put an await point after each emit or after some emits.
///                 // This allows the `take()` operator to function properly.
///                 time::sleep(time::Duration::from_millis(1)).await;
///             }
///             // Signal completion to the subscriber.
///             o.complete();
///         });
///
///         // Return a new `Subscription` with custom unsubscribe logic.
///         Subscription::new(
///             // The provided closure defines the behavior of the subscription when it
///             // is unsubscribed. In this case, it sends a signal to an asynchronous
///             // observable to stop emitting values. If your closure requires Tokio
///             // tasks or channels to send unsubscribe signals, use `UnsubscribeLogic::Future`.
///             UnsubscribeLogic::Future(Box::pin(async move {
///                 if tx.send(UNSUBSCRIBE_SIGNAL).await.is_err() {
///                     println!("Receiver dropped.");
///                 }
///             })),
///             // Store the `JoinHandle` for awaiting completion using the `Subscription`.
///             SubscriptionHandle::JoinTask(join_handle),
///         )
///     });
///
///     // Create the `Subscriber` with a mandatory `next` function, and optional
///     // `complete` function. No need for `error` function in this simple example.
///     let mut observer = Subscriber::on_next(|v| println!("Emitted {}", v));
///     observer.on_complete(|| println!("Completed"));
///
///     // This observable uses Tokio tasks so it will not block the current thread.
///     // Observables are cold so if you comment out the statement bellow nothing
///     // will be emitted.
///     let subscription = observable
///         // `take` utilizes our unsubscribe function to stop background emissions
///         // after a specified item count.
///         .take(15)
///         .map(|v| format!("Mapped {}", v))
///         .delay(1000)
///         .subscribe(observer);
///
///     // Do something else here.
///     println!("Do something while Observable is emitting.");
///
///     // Wait for the subscription to either complete as a Tokio task or join an OS thread.
///     if subscription.join_concurrent().await.is_err() {
///         // Handle error
///     }
///
///     println!("`main` function done")
/// }
///```
///
/// # Example: `Observable` with error handling
///
/// Waits for user input and emits both a value and a completion signal upon success.
/// In case of any errors, it signals them to the attached `Observer`.
///
/// Ensure errors are wrapped in an `Arc` before passing them to the Observer's
/// `error` function.
///
///```no_run
/// use std::{error::Error, fmt::Display, io, sync::Arc};
///
/// use rxr::{subscribe::*, Observable, Observer, Subscribeable};
///
/// #[derive(Debug)]
/// struct MyErr(i32);
///
/// impl Display for MyErr {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         write!(f, "number should be less than 100, you entered {}", self.0)
///     }
/// }
///
/// impl Error for MyErr {}
///
/// // Creates an `Observable<i32>` that processes user input and emits or signals errors.
/// pub fn get_less_than_100() -> Observable<i32> {
///     Observable::new(|mut observer| {
///         let mut input = String::new();
///
///         println!("Please enter an integer (less than 100):");
///
///         if let Err(e) = io::stdin().read_line(&mut input) {
///             // Send input error to the observer.
///             observer.error(Arc::new(e));
///             return Subscription::new(UnsubscribeLogic::Nil, SubscriptionHandle::Nil);
///         }
///
///         match input.trim().parse::<i32>() {
///             Err(e) => {
///                 // Send parsing error to the observer.
///                 observer.error(Arc::new(e));
///             }
///             Ok(num) if num > 100 => {
///                 // Send custom error to the observer.
///                 observer.error(Arc::new(MyErr(num)))
///             }
///             Ok(num) => {
///                 // Emit the parsed value to the observer.
///                 observer.next(num);
///             }
///         }
///
///         // Signal completion if there are no errors.
///         // Note: `complete` does not affect the outcome if `error` was called before it.
///         observer.complete();
///
///         Subscription::new(UnsubscribeLogic::Nil, SubscriptionHandle::Nil)
///     })
/// }
///
/// let observer = Subscriber::new(
///     |input| println!("You entered: {}", input),
///     |e| eprintln!("{}", e),
///     || println!("User input handled"),
/// );
///
/// let mut observable = get_less_than_100();
///
/// observable.subscribe(observer);
///```
#[derive(Clone)]
pub struct Observable<T> {
    subscribe_fn: Arc<Mutex<SubscribeFn<T>>>,
    fused: bool,
    defused: bool,
    pub(crate) subject: bool,
}

impl<T> Observable<T> {
    /// Creates a new `Observable` with the provided subscribe function.
    ///
    /// This method allows you to define custom behavior for the `Observable` by
    /// providing a subscribe function (`sf`), a closure that defines the behavior of
    /// the `Observable` when subscribed. When the `Observable` is subscribed to, the
    /// `sf` function is invoked to manage the delivery of values to the `Subscriber`.
    /// It should also return a `Subscription` that enables unsubscribing and can be
    /// used for awaiting `Tokio` tasks or joining OS threads when the `Observable`
    /// is asynchronous.
    pub fn new(sf: impl FnMut(Subscriber<T>) -> Subscription + Send + Sync + 'static) -> Self {
        Observable {
            subscribe_fn: Arc::new(Mutex::new(Box::new(sf))),
            fused: false,
            defused: false,
            subject: false,
        }
    }

    /// Creates an empty observable.
    ///
    /// The resulting observable does not emit any values and immediately completes
    /// upon subscription. It serves as a placeholder or a base case for some
    /// observable operations.
    #[must_use]
    pub fn empty() -> Self {
        Observable {
            subscribe_fn: Arc::new(Mutex::new(Box::new(|_| {
                Subscription::new(UnsubscribeLogic::Nil, SubscriptionHandle::Nil)
            }))),
            fused: false,
            defused: false,
            subject: false,
        }
    }

    /// Fuse the observable, allowing it to complete at most once.
    ///
    /// If `complete()` is called on a fused observable, any subsequent emissions
    /// will have no effect. This ensures that the observable is closed after the
    /// first completion call.
    ///
    /// By default, observables are not fused, allowing them to emit values even
    /// after calling `complete()` and permitting multiple calls to `complete()`.
    /// When an observable emits an error, it is considered closed and will no longer
    /// emit any further values, regardless of being fused or not.
    ///
    /// # Notes
    ///
    /// `fuse()` does not unsubscribe ongoing emissions from the observable;
    /// it simply ignores them after the first `complete()` call, ensuring that no
    /// more values are emitted.
    #[must_use]
    pub fn fuse(mut self) -> Self {
        self.fused = true;
        self.defused = false;
        self
    }

    /// Defuse the observable, allowing it to complete and emit values after calling
    /// `complete()`.
    ///
    /// Observables are defused by default, enabling them to emit values even after
    /// completion and allowing multiple calls to `complete()`. Calling `defuse()` is
    /// not necessary unless the observable has been previously fused using
    /// [`fuse()`](#method.fuse). Once an observable is defused, it can emit values
    /// and call `complete()` multiple times on its observers.
    ///
    /// # Notes
    ///
    /// Defusing an observable does not allow it to emit an error after the first
    /// error emission. Once an error is emitted, the observable is considered closed
    /// and will not emit any further values, regardless of being defused or not.
    #[must_use]
    pub fn defuse(mut self) -> Self {
        self.fused = false;
        self.defused = true;
        self
    }
}

/// The `ObservableExt` trait provides a set of extension methods that can be applied
/// to observables to transform and manipulate their behavior.
///
/// This trait enhances the capabilities of the `Observable` struct by allowing users
/// to chain operators together, creating powerful reactive pipelines.
#[allow(clippy::module_name_repetitions)]
pub trait ObservableExt<T: 'static>: Subscribeable<ObsType = T> {
    /// Transforms the items emitted by the observable using a transformation
    /// function.
    ///
    /// The transformation function `f` is applied to each item emitted by the
    /// observable, and the resulting value is emitted by the resulting observable.
    fn map<U, F>(mut self, f: F) -> Observable<U>
    where
        Self: Sized + Send + Sync + 'static,
        F: FnOnce(T) -> U + Copy + Sync + Send + 'static,
        U: 'static,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let mut u = Subscriber::new(
                move |v| {
                    let t = f(v);
                    o_shared.lock().unwrap().next(t);
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Filters the items emitted by the observable based on a predicate function.
    ///
    /// Only items for which the predicate function returns `true` will be emitted
    /// by the resulting observable.
    fn filter<P>(mut self, predicate: P) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
        P: (FnOnce(&T) -> bool) + Copy + Sync + Send + 'static,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let mut u = Subscriber::new(
                move |v| {
                    if predicate(&v) {
                        o_shared.lock().unwrap().next(v);
                    }
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Skips the first `n` items emitted by the observable and then emits the rest.
    ///
    /// If `n` is greater than or equal to the total number of items, it behaves as
    /// if the observable is complete and emits no items.
    fn skip(mut self, n: usize) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let mut n = n;
            let mut u = Subscriber::new(
                move |v| {
                    if n > 0 {
                        n -= 1;
                        return;
                    }
                    o_shared.lock().unwrap().next(v);
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Delays the emissions from the observable by the specified number of
    /// milliseconds.
    ///
    /// The `delay` operator introduces a time delay for emissions from the
    /// observable, determined by the specified duration.
    fn delay(mut self, num_of_ms: u64) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let mut u = Subscriber::new(
                move |v| {
                    std::thread::sleep(Duration::from_millis(num_of_ms));
                    o_shared.lock().unwrap().next(v);
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Accumulates values emitted by an observable over time, producing an accumulated
    /// result based on an accumulator function applied to each emitted value.
    ///
    /// The `scan` operator applies an accumulator function over the values emitted by
    /// the source observable. It accumulates values into a single accumulated result,
    /// and each new value emitted by the source observable contributes to this
    /// accumulation. The accumulated result is emitted by the resulting observable.
    /// `seed` is optional. If omitted, the first emitted value is used as the `seed`.
    fn scan<U, F>(mut self, acc: F, seed: Option<U>) -> Observable<U>
    where
        Self: Sized + Send + Sync + 'static,
        F: FnOnce(U, T) -> U + Copy + Sync + Send + 'static,
        U: From<T> + Clone + Send + Sync + 'static,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        // let acc = Arc::new(Mutex::new(acc));

        let mut observable = Observable::new(move |o| {
            let state = Arc::new(Mutex::new(seed.clone()));
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);
            let state_cl = Arc::clone(&state);
            // let acc_cl = Arc::clone(&acc);

            let mut u = Subscriber::new(
                move |v: T| {
                    if let Ok(mut state) = state_cl.lock() {
                        if state.is_none() {
                            *state = Some(std::convert::Into::into(v));
                        } else {
                            *state = state.as_ref().map(|s| acc(s.clone(), v));
                        }
                        o_shared
                            .lock()
                            .unwrap()
                            .next(state.as_ref().unwrap().clone());
                    }
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    // fn scan_a<F>(mut self, acc: F, seed: Option<T>) -> ScanObservable<T>
    // where
    //     Self: Sized + Send + Sync + 'static,
    //     F: FnMut(T, T) -> T + Sync + Send + 'static,
    //     T: Clone + Send,
    // {
    //     let subject = self.is_subject();
    //     let (fused, defused) = self.get_fused();

    //     let mut observable = ScanObservable::new(
    //         move |o| {
    //             let fused = o.fused;
    //             let defused = o.defused;

    //             self.set_fused(fused, defused);
    //             self.subscribe(o)
    //         },
    //         acc,
    //         seed,
    //     );
    //     observable.set_subject_indicator(subject);
    //     observable.set_fused(fused, defused);
    //     observable
    // }

    /// Creates a connectable observable from the source observable.
    ///
    /// This operator converts the source observable into a connectable observable,
    /// allowing multiple subscribers to connect to the same source without causing
    /// multiple subscriptions to the underlying source.
    ///
    /// The actual emission of values from the source observable will occur only
    /// after calling the [`connect()`] method on the resulting `Connectable` instance.
    ///
    /// [`connect()`]: multicast/struct.Connectable.html#method.connect
    fn connectable(self) -> Connectable<T>
    where
        Self: Send + Sync + Sized + 'static,
        T: Send + Sync + Clone,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        let mut connectable_observable = Connectable::new(Arc::new(Mutex::new(self)));
        connectable_observable.set_subject_indicator(subject);
        connectable_observable.set_fused(fused, defused);
        connectable_observable
    }

    /// Emits only the first item emitted by the source observable that satisfies the
    /// provided `predicate`, optionally applying a default value if no items match
    /// the `predicate`.
    ///
    /// The `predicate` function takes two arguments: the emitted item `T` and the index
    /// `usize` of the emission. It should return `true` if the item meets the criteria.
    ///
    /// If a `default_value` is provided and no item satisfies the `predicate`, the
    /// observable emits the `default_value` instead. If no default value is provided
    /// and no item satisfies the `predicate`, the observable emits an `EmptyError`.
    ///
    /// The `first` operator unsubscribes from the background emissions as soon as it
    /// takes the first item that satisfies the `predicate`.
    fn first<F>(mut self, predicate: F, default_value: Option<T>) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
        F: FnOnce(T, usize) -> bool + Copy + Send + Sync + 'static,
        T: Clone + Send + Sync,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;
            let mut default_value = default_value.clone();

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let mut signal_sent = false;
            let emitted = Arc::new(Mutex::new(false));
            let emitted_cl = Arc::clone(&emitted);

            let (tx, rx) = setup_unsubscribe_channel();
            let mut index = 0;
            let mut u = Subscriber::new(
                move |v: T| {
                    if !signal_sent && predicate(v.clone(), index) {
                        o_shared.lock().unwrap().next(v);
                        signal_sent = true;
                        *emitted.lock().unwrap() = true;
                        tx.send_unsubscribe_signal();
                    }
                    index += 1;
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    if let (Ok(mut observer), Ok(emitted)) = (o_cloned_c.lock(), emitted_cl.lock())
                    {
                        if !*emitted {
                            // Observable did not emitted value.
                            if let Some(v) = default_value.take() {
                                // There is a default value.
                                observer.next(v);
                                observer.complete();
                            } else {
                                // There is no default value.
                                observer.error(Arc::new(EmptyError));
                            }
                            return;
                        }
                        // Observable did emitted value.
                        observer.complete();
                    }
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            let unsubscriber = self.subscribe(u);
            rx.unsubscribe_background_emissions(&self, unsubscriber)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Zips the values emitted by multiple observables into a single observable.
    ///
    /// This method combines the values emitted by multiple observables into a single
    /// observable, emitting a vector containing the latest value from each observable
    /// in order when all observables have emitted a new value. This method is
    /// non-blocking and combines the latest values emitted by observables without
    /// waiting for completion. It completes as soon as the first observable in the
    /// sequence completes and attempts to unsubscribe all zipped observables. If any
    /// observable within the sequence encounters an error, it stops emissions, emits
    /// that error, and tries to unsubscribe all observables in the sequence.
    #[allow(clippy::too_many_lines)]
    fn zip(mut self, observable_inputs: Vec<Observable<T>>) -> Observable<Vec<T>>
    where
        Self: Clone + Sized + Send + Sync + 'static,
        T: Clone + Send,
    {
        use std::collections::HashMap;

        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        let mut observable = Observable::new(move |o| {
            use std::task::Poll;

            #[allow(clippy::needless_pass_by_value)]
            fn unsubscribe_stored_subscriptions(
                subscriptions_store: Arc<Mutex<Vec<Subscription>>>,
                is_subject: bool,
            ) {
                // To avoid dead-lock, we skip calling `unsubscribe()` if source
                // observable is one of the Subject variants.
                if is_subject {
                    if let Ok(mut s) = subscriptions_store.lock() {
                        s.pop();
                    }
                }
                if let Ok(mut s) = subscriptions_store.lock() {
                    while let Some(u) = s.pop() {
                        u.unsubscribe();
                    }
                }
            }

            let is_subject = self.is_subject();
            let mut observable_inputs: VecDeque<Observable<T>> = observable_inputs.clone().into();
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let input_len = observable_inputs.len();
            let all_emits_collect = Arc::new(Mutex::new(HashMap::with_capacity(input_len)));

            let subscriptions_store = Arc::new(Mutex::new(Vec::with_capacity(input_len)));
            let subscriptions_store_cl = Arc::clone(&subscriptions_store);
            let subscriptions_store_cl2 = Arc::clone(&subscriptions_store);
            let subscriptions_store_cl3 = Arc::clone(&subscriptions_store);
            let tokio_handle = tokio::runtime::Handle::try_current();

            let mut idx = 0;
            while let Some(mut input) = observable_inputs.pop_front() {
                let inner_emits_collect = VecDeque::with_capacity(16);
                all_emits_collect
                    .lock()
                    .unwrap()
                    .insert(idx, inner_emits_collect);

                let all_emits_collect_cl = Arc::clone(&all_emits_collect);
                let all_emits_collect_cl2 = Arc::clone(&all_emits_collect);
                let all_emits_collect_cl3 = Arc::clone(&all_emits_collect);

                let inner_subscriber = Subscriber::new(
                    move |v: T| {
                        let all_emits_collect_cl = Arc::clone(&all_emits_collect_cl);
                        if let Some(inner_emits) =
                            all_emits_collect_cl.lock().unwrap().get_mut(&idx)
                        {
                            inner_emits.push_back(EmittedValue::Success(v));
                        };
                    },
                    move |e| {
                        if let Some(inner_emits) =
                            all_emits_collect_cl2.lock().unwrap().get_mut(&idx)
                        {
                            inner_emits.push_back(EmittedValue::Error(e));
                        }
                    },
                    move || {
                        if let Some(inner_emits) =
                            all_emits_collect_cl3.lock().unwrap().get_mut(&idx)
                        {
                            inner_emits.push_back(EmittedValue::Complete);
                        }
                    },
                );
                let subscriptions_store = Arc::clone(&subscriptions_store);
                let subscription = input.subscribe(inner_subscriber);
                subscriptions_store.lock().unwrap().push(subscription);
                idx += 1;
            }

            let mut unsubscribed = false;
            let mut u = Subscriber::new(
                move |v| {
                    if unsubscribed {
                        return;
                    }
                    let mut values = Vec::with_capacity(input_len);
                    values.push(v);
                    let mut unsub = false;
                    let mut i = 0;
                    loop {
                        std::thread::sleep(Duration::from_millis(1));
                        if let Some(s) = all_emits_collect.lock().unwrap().get_mut(&i) {
                            match s.pop_front() {
                                Some(EmittedValue::Success(e)) => {
                                    values.push(e);
                                    i += 1;
                                }
                                Some(EmittedValue::Complete) => {
                                    unsub = true;
                                    break;
                                }
                                Some(EmittedValue::Error(e)) => {
                                    unsub = true;
                                    o_shared.lock().unwrap().error(e);
                                    break;
                                }
                                None => (),
                            }
                        }
                        if i == input_len {
                            break;
                        }
                        if tokio::runtime::Handle::try_current().is_ok() {
                            let ftr = std::future::poll_fn(|cx| {
                                cx.waker().wake_by_ref();
                                Poll::Ready::<()>(())
                            });
                            tokio::task::spawn(async {
                                ftr.await;
                            });
                        }
                    }
                    if unsub {
                        unsubscribe_stored_subscriptions(
                            subscriptions_store_cl.clone(),
                            is_subject,
                        );
                        unsubscribed = true;
                        return;
                    }
                    o_shared.lock().unwrap().next(values);
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                    unsubscribe_stored_subscriptions(subscriptions_store_cl2.clone(), is_subject);
                },
                move || {
                    // If outer observable completes first notify all inner
                    // observables to complete.
                    o_cloned_c.lock().unwrap().complete();
                    unsubscribe_stored_subscriptions(subscriptions_store_cl3.clone(), is_subject);
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);

            let mut outer_subscription = self.subscribe(u);
            let handle = outer_subscription.subscription_future;
            outer_subscription.subscription_future = SubscriptionHandle::Nil;
            subscriptions_store.lock().unwrap().push(outer_subscription);

            if tokio_handle.is_ok() {
                return Subscription::new(
                    UnsubscribeLogic::Future(Box::pin(async move {
                        unsubscribe_stored_subscriptions(subscriptions_store, false);
                    })),
                    handle,
                );
            }
            Subscription::new(
                UnsubscribeLogic::Logic(Box::new(move || {
                    unsubscribe_stored_subscriptions(subscriptions_store, false);
                })),
                handle,
            )
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Emits at most the first `n` items emitted by the observable, then
    /// unsubscribes.
    ///
    /// If the observable emits more than `n` items, this operator will only allow
    /// the first `n` items to be emitted. After emitting `n` items, it will
    /// unsubscribe from the observable.
    ///
    /// # Notes
    ///
    /// For `Subject` variants, using `take(n)` as the initial operator
    /// (e.g., `subject.take(n).delay(n)`) will not call unsubscribe and remove
    /// registered subscribers for performance reasons.
    ///
    /// However, when used as a non-initial operator (e.g., `subject.delay(n).take(n)`),
    /// it will call unsubscribe and remove registered subscribers.
    fn take(mut self, n: usize) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        let mut i = 0;

        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let (tx, rx) = setup_unsubscribe_channel();
            let mut signal_sent = false;

            // Alternative implementation for Subject's if desired behavior is to
            // skip call to unsubscribe() when take() operator is used. This might be
            // used for performance reasons because opening a channel and spawning a
            // new thread can be skipped when this operator is used on Subject's.
            if self.is_subject() {
                signal_sent = true;
            }

            let mut u = Subscriber::new(
                move |v| {
                    if i < n {
                        i += 1;
                        o_shared.lock().unwrap().next(v);
                    } else if !signal_sent {
                        signal_sent = true;
                        tx.send_unsubscribe_signal();
                    }
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = true;
            self.set_fused(fused, defused);

            let unsubscriber = self.subscribe(u);
            rx.unsubscribe_background_emissions(&self, unsubscriber)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Continuously emits the values from the source observable until an event occurs,
    /// triggered by an emitted value from a separate `notifier` observable.
    ///
    /// The `takeUntil` operator subscribes to and starts replicating the behavior of
    /// the source observable. Simultaneously, it observes a second observable,
    /// referred to as the `notifier`, provided by the user. When the `notifier` emits
    /// a value, the resulting observable stops replicating the source observable and
    /// completes. If the `notifier` completes without emitting any value, `takeUntil`
    /// will pass all values from the source observable. When the `notifier` triggers
    /// its first emission `take_until` unsubscribes from ongoing emissions of the
    /// source observable.
    ///
    /// The `take_until` operator accepts a second parameter, `unsubscribe_notifier`,
    /// allowing control over whether `takeUntil` will attempt to unsubscribe from
    /// emissions of the `notifier` observable. When set to `true`, `takeUntil`
    /// actively attempts to unsubscribe from the `notifier`'s emissions. When set to
    /// `false`, `takeUntil` refrains from attempting to unsubscribe from the
    /// `notifier`, allowing the emissions to continue unaffected.
    fn take_until<U: 'static>(
        mut self,
        notifier: Observable<U>,
        unsubscribe_notifier: bool,
    ) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
    {
        let notifier = Arc::new(Mutex::new(notifier));
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();

        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let (tx, rx) = setup_unsubscribe_channel();
            let mut signal_sent = false;

            let notifier_next_called = Arc::new(Mutex::new(false));
            let notifier_next_called_cl = Arc::clone(&notifier_next_called);

            // Make an inner Observer which will set `notifier called` flag.
            let observer =
                Subscriber::on_next(move |_: U| *notifier_next_called_cl.lock().unwrap() = true);

            let notifier = Arc::clone(&notifier);
            let subscription = Arc::new(Mutex::new(None));
            let subscription_cl = Arc::clone(&subscription);

            // If Tokio is used, subscribe notifier in a Tokio task even if runtime
            // flavor is `current_thread`. This is because notifier can start Tokio
            // tasks and they can't be started in OS thread. Program would panic instead.
            if tx.is_tokio_used() {
                tokio::task::spawn(async move {
                    let subscription = notifier.lock().unwrap().subscribe(observer);
                    *subscription_cl.lock().unwrap() = Some(subscription);
                });
            } else {
                std::thread::spawn(move || {
                    let subscription = notifier.lock().unwrap().subscribe(observer);
                    *subscription_cl.lock().unwrap() = Some(subscription);
                });
            }

            // Alternative implementation for Subject's if desired behavior is to
            // skip call to unsubscribe() when take() operator is used. This might be
            // used for performance reasons because opening a channel and spawning a
            // new thread can be skipped when this operator is used on Subject's.
            if self.is_subject() {
                signal_sent = true;
            }

            let mut u = Subscriber::new(
                move |v| {
                    if !(*notifier_next_called.lock().unwrap()) {
                        o_shared.lock().unwrap().next(v);
                    } else if !signal_sent {
                        signal_sent = true;
                        tx.send_unsubscribe_signal();
                        if unsubscribe_notifier {
                            if let Some(s) = subscription.lock().unwrap().take() {
                                s.unsubscribe();
                            }
                        }
                    } else if unsubscribe_notifier {
                        if let Some(s) = subscription.lock().unwrap().take() {
                            s.unsubscribe();
                        }
                    }
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = true;
            self.set_fused(fused, defused);

            let unsubscriber = self.subscribe(u);
            rx.unsubscribe_background_emissions(&self, unsubscriber)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Continues emitting values from the source observable as long as each value
    /// meets the specified `predicate` criteria. The operation concludes immediately
    /// upon encountering the first value that doesn't satisfy the `predicate`.
    ///
    /// Upon subscription, `takeWhile` starts replicating the source observable.
    /// Every emitted value from the source is evaluated by the `predicate` function,
    /// returning a boolean that represents a condition for the source values. The
    /// resulting observable continues emitting source values until the `predicate`
    /// yields `false`. When the specified condition is no longer met, `takeWhile`
    /// ceases mirroring the source, subsequently unsubscribing from the source to
    /// stop background emissions.
    fn take_while<P>(mut self, predicate: P) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
        P: FnOnce(&T) -> bool + Copy + Sync + Send + 'static,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();

        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let (tx, rx) = setup_unsubscribe_channel();
            let mut signal_sent = false;

            // Alternative implementation for Subject's if desired behavior is to
            // skip call to unsubscribe() when take() operator is used. This might be
            // used for performance reasons because opening a channel and spawning a
            // new thread can be skipped when this operator is used on Subject's.
            if self.is_subject() {
                signal_sent = true;
            }

            let mut u = Subscriber::new(
                move |v| {
                    if predicate(&v) {
                        o_shared.lock().unwrap().next(v);
                    } else if !signal_sent {
                        signal_sent = true;
                        tx.send_unsubscribe_signal();
                    }
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = true;
            self.set_fused(fused, defused);

            let unsubscriber = self.subscribe(u);
            rx.unsubscribe_background_emissions(&self, unsubscriber)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Produces an observable that emits, at maximum, the final `count` values
    /// emitted by the source observable.
    ///
    /// Utilizing `takeLast` creates an observable that retains up to 'count' values
    /// in memory until the source observable completes. Upon completion, it delivers
    /// all stored values in their original order to the consumer and signals completion.
    ///
    /// In scenarios where the source completes before reaching the specified `count`
    /// in `takeLast`, it emits all received values up to that point and then signals completion.
    ///
    /// # Notes
    ///
    /// When applied to an observable that never completes, `takeLast` yields an
    /// observable that doesn't emit any value.
    fn take_last(mut self, count: usize) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
        T: Send,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();

        let mut observable = Observable::new(move |o| {
            let last_values_buffer = Arc::new(Mutex::new(VecDeque::with_capacity(count)));
            let last_values_buffer_cl = Arc::clone(&last_values_buffer);

            let fused = o.fused;
            let defused = o.defused;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let i = Arc::new(Mutex::new(0));
            let i_cl = Arc::clone(&i);

            let mut u = Subscriber::new(
                move |v| {
                    if count == 0 {
                        return;
                    }
                    if let (Ok(mut counter), Ok(mut last_values_buffer)) =
                        (i.lock(), last_values_buffer_cl.lock())
                    {
                        *counter += 1;
                        if *counter > count {
                            last_values_buffer.pop_front();
                        }
                        last_values_buffer.push_back(v);
                    }
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    if let (Ok(mut o), Ok(mut last_values_buffer)) =
                        (o_shared.lock(), last_values_buffer.lock())
                    {
                        while let Some(item) = last_values_buffer.pop_front() {
                            o.next(item);
                        }
                        let _ = i_cl.lock().map(|mut counter| *counter = 0);
                        o.complete();
                    }
                },
            );
            u.take_wrapped = true;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// The `tap` operator allows you to intercept the items emitted by an observable
    /// and perform side effects on those items without modifying the emitted data or
    /// the stream itself.
    ///
    /// This operator is used primarily for side effects. It allows you to perform
    /// actions or operations on the items emitted by an observable without affecting
    /// the stream itself. The `tap` operator is best used for debugging, logging, or
    /// performing actions that don't change the emitted values but are necessary for
    /// monitoring or debugging purposes such as console logging, data inspection,
    /// or triggering some external action based on the emitted values.
    ///
    /// ```text
    /// let log_observer = Subscriber::new(
    ///     |v| println!("Filtered {}", v),
    ///     |e| println!("Filtered error {}", e),
    ///     || println!("Filtered complete")
    /// );
    ///
    /// observable
    ///     .tap(Subscriber::on_next(|v| println!("Before filtering: {}", v)))
    ///     .filter(|v| v % 2 == 0)
    ///     .tap(log_observer)
    ///     .subscribe(observer);
    /// ```
    fn tap(mut self, observer: Subscriber<T>) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
        T: Clone,
    {
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();
        let observer = Arc::new(Mutex::new(observer));
        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let observer = Arc::clone(&observer);
            let observer_cl = Arc::clone(&observer);
            let observer_e = Arc::clone(&observer);

            let mut u = Subscriber::new(
                move |v: T| {
                    if let Ok(mut s) = observer.lock() {
                        s.next(v.clone());
                    }
                    o_shared.lock().unwrap().next(v);
                },
                move |observable_error| {
                    if let Ok(mut s) = observer_e.lock() {
                        s.error(observable_error.clone());
                    }
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    if let Ok(mut s) = observer_cl.lock() {
                        s.complete();
                    }
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Merges the current observable with a vector of observables, emitting items
    /// from all of them concurrently.
    fn merge(mut self, mut sources: Vec<Observable<T>>) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
    {
        fn wrap_subscriber<S: 'static>(
            s: Arc<Mutex<Subscriber<S>>>,
            is_fused: bool,
            is_defused: bool,
            is_take_wrapped: bool,
        ) -> Subscriber<S> {
            let s_complete = s.clone();
            let s_error = s.clone();

            let mut s = Subscriber::new(
                move |v| {
                    s.lock().unwrap().next(v);
                },
                move |e| {
                    s_error.lock().unwrap().error(e);
                },
                move || {
                    s_complete.lock().unwrap().complete();
                },
            );
            s.take_wrapped = is_take_wrapped;
            s.set_fused(is_fused, is_defused);
            s
        }

        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();

        let mut observable = Observable::new(move |o| {
            let take_wrapped = o.take_wrapped;
            let fused = o.fused;
            let defused = o.defused;

            // o.fused = false;
            // o.defused = false;
            let o = Arc::new(Mutex::new(o));
            let mut subscriptions = Vec::with_capacity(sources.len());

            let mut use_tokio_task = false;
            self.set_fused(fused, defused);
            let s = self.subscribe(wrap_subscriber(o.clone(), fused, defused, take_wrapped));

            if let UnsubscribeLogic::Future(_) = &s.unsubscribe_logic {
                use_tokio_task = true;
            }

            for source in &mut sources {
                let wrapped = wrap_subscriber(o.clone(), fused, defused, false);
                // source.set_fused((fused, defused));
                let subscription = source.subscribe(wrapped);

                if let UnsubscribeLogic::Future(_) = &subscription.unsubscribe_logic {
                    use_tokio_task = true;
                }
                subscriptions.push(subscription);
            }

            // If Tokio is used with `current_thread` runtime flavor, returned
            // Subscriber will be `UnsubscribeLogic::Logic` so that `take()` can
            // unsubscribe background emissions in all cases.
            if let Ok(handle) = s.runtime_handle.as_ref() {
                if let tokio::runtime::RuntimeFlavor::CurrentThread = handle.runtime_flavor() {
                    use_tokio_task = false;
                }
            }
            subscriptions.push(s);

            let subscriptions = Arc::new(Mutex::new(Some(subscriptions)));
            let sc = Arc::clone(&subscriptions);

            if use_tokio_task {
                return Subscription::new(
                    UnsubscribeLogic::Future(Box::pin(async move {
                        let subscriptions = subscriptions.lock().unwrap().take();

                        if let Some(subscriptions) = subscriptions {
                            for subscription in subscriptions {
                                subscription.unsubscribe();
                            }
                        }
                    })),
                    SubscriptionHandle::JoinSubscriptions(SubscriptionCollection::new(sc, true)),
                );
            }
            Subscription::new(
                UnsubscribeLogic::Logic(Box::new(move || {
                    let subscriptions = subscriptions.lock().unwrap().take();

                    if let Some(subscriptions) = subscriptions {
                        for subscription in subscriptions {
                            subscription.unsubscribe();
                        }
                    }
                })),
                SubscriptionHandle::JoinSubscriptions(SubscriptionCollection::new(sc, false)),
            )
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Merges the current observable with another observable, emitting items from
    /// both concurrently.
    fn merge_one(mut self, mut source: Observable<T>) -> Observable<T>
    where
        Self: Sized + Send + Sync + 'static,
    {
        fn wrap_subscriber<S: 'static>(
            s: Arc<Mutex<Subscriber<S>>>,
            is_fused: bool,
            is_defused: bool,
            is_take_wrapped: bool,
        ) -> Subscriber<S> {
            let s_complete = s.clone();
            let s_error = s.clone();

            let mut s = Subscriber::new(
                move |v| {
                    s.lock().unwrap().next(v);
                },
                move |e| {
                    s_error.lock().unwrap().error(e);
                },
                move || {
                    s_complete.lock().unwrap().complete();
                },
            );
            s.take_wrapped = is_take_wrapped;
            s.set_fused(is_fused, is_defused);
            s
        }

        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();

        let mut observable = Observable::new(move |o| {
            let take_wrapped = o.take_wrapped;
            let fused = o.fused;
            let defused = o.defused;

            // o.fused = false;
            // o.defused = false;
            let o = Arc::new(Mutex::new(o));

            let wrapped = wrap_subscriber(o.clone(), fused, defused, take_wrapped);
            let wrapped2 = wrap_subscriber(o, fused, defused, false);

            let mut use_tokio_task = false;

            self.set_fused(fused, defused);
            let s1 = self.subscribe(wrapped);
            let s2 = source.subscribe(wrapped2);

            match (&s1.unsubscribe_logic, &s2.unsubscribe_logic) {
                (UnsubscribeLogic::Future(_), _) | (_, UnsubscribeLogic::Future(_)) => {
                    use_tokio_task = true;
                }
                _ => (),
            }

            // If Tokio is used with `current_thread` runtime flavor returned
            // Subscriber will be `UnsubscribeLogic::Logic` so that `take()` can
            // unsubscribe background emissions in all cases.
            if let Ok(handle) = s1.runtime_handle.as_ref() {
                if let tokio::runtime::RuntimeFlavor::CurrentThread = handle.runtime_flavor() {
                    use_tokio_task = false;
                }
            }
            let subscriptions = vec![s1, s2];
            let subscriptions = Arc::new(Mutex::new(Some(subscriptions)));
            let sc = Arc::clone(&subscriptions);

            if use_tokio_task {
                return Subscription::new(
                    UnsubscribeLogic::Future(Box::pin(async move {
                        let subscriptions = subscriptions.lock().unwrap().take();

                        if let Some(subscriptions) = subscriptions {
                            for subscription in subscriptions {
                                subscription.unsubscribe();
                            }
                        }
                    })),
                    SubscriptionHandle::JoinSubscriptions(SubscriptionCollection::new(sc, true)),
                );
            }
            Subscription::new(
                UnsubscribeLogic::Logic(Box::new(move || {
                    let subscriptions = subscriptions.lock().unwrap().take();

                    if let Some(subscriptions) = subscriptions {
                        for subscription in subscriptions {
                            subscription.unsubscribe();
                        }
                    }
                })),
                SubscriptionHandle::JoinSubscriptions(SubscriptionCollection::new(sc, false)),
            )
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Transforms the items emitted by an observable into observables, and flattens
    /// the emissions into a single observable, ignoring previous emissions once a
    /// new one is encountered. This is similar to `map`, but switches to a new inner
    /// observable whenever a new item is emitted.
    ///
    /// # Parameters
    /// - `project`: A closure that maps each source item to an observable.
    ///   The closure returns the observable for each item, and the emissions from
    ///   these observables are flattened into a single observable.
    ///
    /// # Returns
    /// An observable that emits the items from the most recently emitted inner
    /// observable.
    fn switch_map<R: 'static, F>(mut self, project: F) -> Observable<R>
    where
        Self: Sized + Send + Sync + 'static,
        F: (FnMut(T) -> Observable<R>) + Sync + Send + 'static,
    {
        let project = Arc::new(Mutex::new(project));
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();

        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let project = Arc::clone(&project);

            let mut current_subscription: Option<Subscription> = None;

            let mut u = Subscriber::new(
                move |v| {
                    let o_shared = Arc::clone(&o_shared);
                    let o_cloned_e = Arc::clone(&o_shared);
                    let o_cloned_c = Arc::clone(&o_shared);
                    let project = Arc::clone(&project);

                    let mut inner_observable = project.lock().unwrap()(v);
                    drop(project);

                    let inner_subscriber = Subscriber::new(
                        move |k| {
                            o_shared.lock().unwrap().next(k);
                        },
                        move |observable_error| {
                            o_cloned_e.lock().unwrap().error(observable_error);
                        },
                        move || {
                            o_cloned_c.lock().unwrap().complete();
                        },
                    );

                    if let Some(subscription) = current_subscription.take() {
                        subscription.unsubscribe();
                    }

                    let s = inner_observable.subscribe(inner_subscriber);
                    current_subscription = Some(s);
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Transforms the items emitted by the source observable into other observables,
    /// and merges them into a single observable stream.
    ///
    /// This operator applies the provided `project` function to each item emitted by
    /// the source observable. The function returns another observable. The operator
    /// subscribes to these inner observables concurrently and merges their emissions
    /// into one observable stream.
    ///
    /// # Parameters
    ///
    /// - `project`: A closure that maps each item emitted by the source observable
    ///   to another observable.
    ///
    /// # Returns
    ///
    /// An observable that emits items merged from the inner observables produced by
    /// the `project` function.
    fn merge_map<R: 'static, F>(mut self, project: F) -> Observable<R>
    where
        Self: Sized + Send + Sync + 'static,
        F: (FnMut(T) -> Observable<R>) + Sync + Send + 'static,
    {
        let project = Arc::new(Mutex::new(project));
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();

        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let project = Arc::clone(&project);

            let mut u = Subscriber::new(
                move |v| {
                    let o_shared = Arc::clone(&o_shared);
                    let o_cloned_e = Arc::clone(&o_shared);
                    let o_cloned_c = Arc::clone(&o_shared);
                    let project = Arc::clone(&project);

                    let mut inner_observable = project.lock().unwrap()(v);
                    drop(project);

                    let inner_subscriber = Subscriber::new(
                        move |k| {
                            o_shared.lock().unwrap().next(k);
                        },
                        move |observable_error| {
                            o_cloned_e.lock().unwrap().error(observable_error);
                        },
                        move || {
                            o_cloned_c.lock().unwrap().complete();
                        },
                    );
                    inner_observable.subscribe(inner_subscriber);
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Transforms the items emitted by the source observable into other observables
    /// using a closure, and concatenates them into a single observable stream,
    /// waiting for each inner observable to complete before moving to the next.
    ///
    /// This operator applies the provided `project` function to each item emitted by
    /// the source observable. The function returns another observable. The operator
    /// subscribes to these inner observables sequentially and concatenates their
    /// emissions into one observable stream.
    ///
    /// # Parameters
    ///
    /// - `project`: A closure that maps each item emitted by the source observable
    ///   to another observable.
    ///
    /// # Returns
    ///
    /// An observable that emits items concatenated from the inner observables
    /// produced by the `project` function.
    fn concat_map<R: 'static, F>(mut self, project: F) -> Observable<R>
    where
        Self: Sized + Send + Sync + 'static,
        F: (FnMut(T) -> Observable<R>) + Sync + Send + 'static,
    {
        let project = Arc::new(Mutex::new(project));
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();

        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let project = Arc::clone(&project);

            let pending_observables: Arc<Mutex<PendingObservables<R>>> =
                Arc::new(Mutex::new(VecDeque::new()));

            let mut first_pass = true;

            let mut u = Subscriber::new(
                move |v| {
                    let o_shared = Arc::clone(&o_shared);
                    let o_cloned_e = Arc::clone(&o_shared);
                    let o_cloned_c = Arc::clone(&o_shared);
                    let po_cloned = Arc::clone(&pending_observables);
                    let project = Arc::clone(&project);

                    let mut inner_observable = project.lock().unwrap()(v);
                    drop(project);

                    let inner_subscriber = Subscriber::new(
                        move |k| o_shared.lock().unwrap().next(k),
                        move |observable_error| {
                            o_cloned_e.lock().unwrap().error(observable_error);
                        },
                        move || {
                            o_cloned_c.lock().unwrap().complete();
                            if let Some((mut io, is)) = po_cloned.lock().unwrap().pop_front() {
                                io.subscribe(is);
                            }
                        },
                    );

                    if first_pass {
                        inner_observable.subscribe(inner_subscriber);
                        first_pass = false;
                        return;
                    }
                    pending_observables
                        .lock()
                        .unwrap()
                        .push_back((inner_observable, inner_subscriber));
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }

    /// Maps each item emitted by the source observable to an inner observable using
    /// a closure. It subscribes to these inner observables, ignoring new items until
    /// the current inner observable completes.
    ///
    /// # Parameters
    ///
    /// - `project`: A closure that maps each item to an inner observable.
    ///
    /// # Returns
    ///
    /// An observable that emits inner observables exclusively. Inner observables do
    /// not emit and remain ignored if a preceding inner observable is still emitting.
    /// The emission of a subsequent inner observable is allowed only after the
    /// current one completes its emission.
    fn exhaust_map<R: 'static, F>(mut self, project: F) -> Observable<R>
    where
        Self: Sized + Send + Sync + 'static,
        F: (FnMut(T) -> Observable<R>) + Sync + Send + 'static,
    {
        let project = Arc::new(Mutex::new(project));
        let subject = self.is_subject();
        let (fused, defused) = self.get_fused();

        let mut observable = Observable::new(move |o| {
            let fused = o.fused;
            let defused = o.defused;
            let take_wrapped = o.take_wrapped;

            let o_shared = Arc::new(Mutex::new(o));
            let o_cloned_e = Arc::clone(&o_shared);
            let o_cloned_c = Arc::clone(&o_shared);

            let project = Arc::clone(&project);

            let active_subscription = Arc::new(Mutex::new(false));
            let guard = Arc::new(Mutex::new(true));

            let mut u = Subscriber::new(
                move |v| {
                    let as_cloned = Arc::clone(&active_subscription);
                    let as_cloned2 = Arc::clone(&active_subscription);
                    let project = Arc::clone(&project);

                    let _guard = guard.lock().unwrap();

                    // Check if previous subscription completed.
                    let is_previous_subscription_active = *as_cloned.lock().unwrap();

                    // if hn {
                    //     println!("TRY TO SEND ??????????????????????????????");
                    //     return;
                    // }
                    // else {
                    //     println!("SENT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                    //     *as_cloned.lock().unwrap() = true;
                    // }

                    let o_shared = Arc::clone(&o_shared);
                    let o_cloned_e = Arc::clone(&o_shared);
                    let o_cloned_c = Arc::clone(&o_shared);

                    let mut inner_observable = project.lock().unwrap()(v);
                    drop(project);

                    let inner_subscriber = Subscriber::new(
                        move |k| o_shared.lock().unwrap().next(k),
                        move |observable_error| {
                            o_cloned_e.lock().unwrap().error(observable_error);
                        },
                        move || {
                            o_cloned_c.lock().unwrap().complete();

                            // Mark this inner subscription as completed so that next
                            // one can be allowed to emit all of its values.
                            *as_cloned2.lock().unwrap() = false;
                        },
                    );

                    // TODO: move this check at the top of the function and return early.
                    // Do not subscribe current inner subscription if previous one is active.
                    if !is_previous_subscription_active {
                        // tokio::task::spawn(async move {
                        // Mark this inner subscription as active so other following
                        // subscriptions are rejected until this one completes.
                        *as_cloned.lock().unwrap() = true;
                        inner_observable.subscribe(inner_subscriber);
                        // });
                    }
                },
                move |observable_error| {
                    o_cloned_e.lock().unwrap().error(observable_error);
                },
                move || {
                    o_cloned_c.lock().unwrap().complete();
                },
            );
            u.take_wrapped = take_wrapped;
            self.set_fused(fused, defused);
            self.subscribe(u)
        });
        observable.set_subject_indicator(subject);
        observable.set_fused(fused, defused);
        observable
    }
}

impl<T> crate::subscription::subscribe::Fuse for Observable<T> {
    fn set_fused(&mut self, fused: bool, defused: bool) {
        self.fused = fused;
        self.defused = defused;
    }

    fn get_fused(&self) -> (bool, bool) {
        (self.fused, self.defused)
    }
}

impl<T: 'static> Subscribeable for Observable<T> {
    type ObsType = T;

    fn subscribe(&mut self, mut v: Subscriber<Self::ObsType>) -> Subscription {
        let (fused, defused) = v.get_fused();

        if defused || (fused && !self.fused) {
            self.defused = v.defused;
            self.fused = v.fused;
        } else {
            v.set_fused(self.fused, self.defused);
        }
        (self.subscribe_fn.lock().unwrap())(v)
    }

    fn is_subject(&self) -> bool {
        self.subject
    }

    fn set_subject_indicator(&mut self, s: bool) {
        self.subject = s;
    }
}

impl<O, T: 'static> ObservableExt<T> for O where O: Subscribeable<ObsType = T> {}

#[cfg(test)]
mod tests;