forked from ReactiveX/RxPY
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
1339 lines (1004 loc) · 38.8 KB
/
__init__.py
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
# pylint: disable=too-many-lines,redefined-outer-name,redefined-builtin
from asyncio import Future
from typing import (
Any,
Callable,
Iterable,
Mapping,
Optional,
Tuple,
TypeVar,
Union,
overload,
)
from . import abc, typing
from ._version import __version__
from .internal.utils import alias
from .notification import Notification
from .observable import ConnectableObservable, GroupedObservable, Observable
from .observer import Observer
from .pipe import compose, pipe
from .subject import Subject
_T = TypeVar("_T")
_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")
_TKey = TypeVar("_TKey")
_TState = TypeVar("_TState")
_A = TypeVar("_A")
_B = TypeVar("_B")
_C = TypeVar("_C")
_D = TypeVar("_D")
_E = TypeVar("_E")
_F = TypeVar("_F")
_G = TypeVar("_G")
def amb(*sources: Observable[_T]) -> Observable[_T]:
"""Propagates the observable sequence that emits first.
.. marble::
:alt: amb
---8--6--9-----------|
--1--2--3---5--------|
----------10-20-30---|
[ amb() ]
--1--2--3---5--------|
Example:
>>> winner = reactivex.amb(xs, ys, zs)
Args:
sources: Sequence of observables to monitor for first emission.
Returns:
An observable sequence that surfaces any of the given sequences,
whichever emitted the first element.
"""
from .observable.amb import amb_ as amb_
return amb_(*sources)
def case(
mapper: Callable[[], _TKey],
sources: Mapping[_TKey, Observable[_T]],
default_source: Optional[Union[Observable[_T], "Future[_T]"]] = None,
) -> Observable[_T]:
"""Uses mapper to determine which source in sources to use.
.. marble::
:alt: case
--1---------------|
a--1--2--3--4--|
b--10-20-30---|
[case(mapper, { 1: a, 2: b })]
---1--2--3--4--|
Examples:
>>> res = reactivex.case(mapper, { '1': obs1, '2': obs2 })
>>> res = reactivex.case(mapper, { '1': obs1, '2': obs2 }, obs0)
Args:
mapper: The function which extracts the value for to test in a
case statement.
sources: An object which has keys which correspond to the case
statement labels.
default_source: [Optional] The observable sequence or Future that will
be run if the sources are not matched. If this is not provided,
it defaults to :func:`empty`.
Returns:
An observable sequence which is determined by a case statement.
"""
from .observable.case import case_
return case_(mapper, sources, default_source)
def catch(*sources: Observable[_T]) -> Observable[_T]:
"""Continues observable sequences which are terminated with an
exception by switching over to the next observable sequence.
.. marble::
:alt: catch
---1---2---3-*
a-7-8-|
[ catch(a) ]
---1---2---3---7-8-|
Examples:
>>> res = reactivex.catch(xs, ys, zs)
Args:
sources: Sequence of observables.
Returns:
An observable sequence containing elements from consecutive observables
from the sequence of sources until one of them terminates successfully.
"""
from .observable.catch import catch_with_iterable_
return catch_with_iterable_(sources)
def catch_with_iterable(sources: Iterable[Observable[_T]]) -> Observable[_T]:
"""Continues observable sequences that are terminated with an
exception by switching over to the next observable sequence.
.. marble::
:alt: catch
---1---2---3-*
a-7-8-|
[ catch(a) ]
---1---2---3---7-8-|
Examples:
>>> res = reactivex.catch([xs, ys, zs])
>>> res = reactivex.catch(src for src in [xs, ys, zs])
Args:
sources: An Iterable of observables; thus, a generator can also
be used here.
Returns:
An observable sequence containing elements from consecutive observables
from the sequence of sources until one of them terminates successfully.
"""
from .observable.catch import catch_with_iterable_
return catch_with_iterable_(sources)
def create(subscribe: typing.Subscription[_T]) -> Observable[_T]:
"""Creates an observable sequence object from the specified
subscription function.
.. marble::
:alt: create
[ create(a) ]
---1---2---3---4---|
Args:
subscribe: Subscription function.
Returns:
An observable sequence that can be subscribed to via the given
subscription function.
"""
return Observable(subscribe)
@overload
def combine_latest(
__a: Observable[_A], __b: Observable[_B]
) -> Observable[Tuple[_A, _B]]:
...
@overload
def combine_latest(
__a: Observable[_A], __b: Observable[_B], __c: Observable[_C]
) -> Observable[Tuple[_A, _B, _C]]:
...
@overload
def combine_latest(
__a: Observable[_A], __b: Observable[_B], __c: Observable[_C], __d: Observable[_D]
) -> Observable[Tuple[_A, _B, _C, _D]]:
...
def combine_latest(*__sources: Observable[Any]) -> Observable[Any]:
"""Merges the specified observable sequences into one observable
sequence by creating a tuple whenever any of the observable
sequences emits an element.
.. marble::
:alt: combine_latest
---a-----b--c------|
--1---2--------3---|
[ combine_latest() ]
---a1-a2-b2-c2-c3--|
Examples:
>>> obs = rx.combine_latest(obs1, obs2, obs3)
Args:
sources: Sequence of observables.
Returns:
An observable sequence containing the result of combining elements from
each source in given sequence.
"""
from .observable.combinelatest import combine_latest_
return combine_latest_(*__sources)
def concat(*sources: Observable[_T]) -> Observable[_T]:
"""Concatenates all of the specified observable sequences.
.. marble::
:alt: concat
---1--2--3--|
--6--8--|
[ concat() ]
---1--2--3----6--8-|
Examples:
>>> res = reactivex.concat(xs, ys, zs)
Args:
sources: Sequence of observables.
Returns:
An observable sequence that contains the elements of each source in
the given sequence, in sequential order.
"""
from .observable.concat import concat_with_iterable_
return concat_with_iterable_(sources)
def concat_with_iterable(sources: Iterable[Observable[_T]]) -> Observable[_T]:
"""Concatenates all of the specified observable sequences.
.. marble::
:alt: concat
---1--2--3--|
--6--8--|
[ concat() ]
---1--2--3----6--8-|
Examples:
>>> res = reactivex.concat_with_iterable([xs, ys, zs])
>>> res = reactivex.concat_with_iterable(for src in [xs, ys, zs])
Args:
sources: An Iterable of observables; thus, a generator can also
be used here.
Returns:
An observable sequence that contains the elements of each given
sequence, in sequential order.
"""
from .observable.concat import concat_with_iterable_
return concat_with_iterable_(sources)
def defer(
factory: Callable[[abc.SchedulerBase], Union[Observable[_T], "Future[_T]"]]
) -> Observable[_T]:
"""Returns an observable sequence that invokes the specified
factory function whenever a new observer subscribes.
.. marble::
:alt: defer
[ defer(1,2,3) ]
---1--2--3--|
---1--2--3--|
Example:
>>> res = reactivex.defer(lambda scheduler: of(1, 2, 3))
Args:
factory: Observable factory function to invoke for each observer
which invokes :func:`subscribe()
<reactivex.Observable.subscribe>` on the resulting sequence.
The factory takes a single argument, the scheduler used.
Returns:
An observable sequence whose observers trigger an invocation
of the given factory function.
"""
from .observable.defer import defer_
return defer_(factory)
def empty(scheduler: Optional[abc.SchedulerBase] = None) -> Observable[Any]:
"""Returns an empty observable sequence.
.. marble::
:alt: empty
[ empty() ]
--|
Example:
>>> obs = reactivex.empty()
Args:
scheduler: [Optional] Scheduler instance to send the termination call
on. By default, this will use an instance of
:class:`ImmediateScheduler <reactivex.scheduler.ImmediateScheduler>`.
Returns:
An observable sequence with no elements.
"""
from .observable.empty import empty_
return empty_(scheduler)
def for_in(
values: Iterable[_T1], mapper: typing.Mapper[_T1, Observable[_T2]]
) -> Observable[_T2]:
"""Concatenates the observable sequences obtained by running the
specified result mapper for each element in the specified values.
.. marble::
:alt: for_in
a--1--2-|
b--10--20-|
[for_in((a, b), lambda i: i+1)]
---2--3--11--21-|
Note:
This is just a wrapper for
:func:`reactivex.concat(map(mapper, values)) <reactivex.concat>`
Args:
values: An Iterable of values to turn into an observable
source.
mapper: A function to apply to each item in the values list to turn
it into an observable sequence; this should return instances of
:class:`reactivex.Observable`.
Returns:
An observable sequence from the concatenated observable
sequences.
"""
mapped: Iterable[Observable[_T2]] = map(mapper, values)
return concat_with_iterable(mapped)
@overload
def fork_join(__a: Observable[_A], __b: Observable[_B]) -> Observable[Tuple[_A, _B]]:
...
@overload
def fork_join(
__a: Observable[_A], __b: Observable[_B], __c: Observable[_C]
) -> Observable[Tuple[_A, _B, _C]]:
...
@overload
def fork_join(
__a: Observable[_A], __b: Observable[_B], __c: Observable[_C], __d: Observable[_D]
) -> Observable[Tuple[_A, _B, _C, _D]]:
...
@overload
def fork_join(
__a: Observable[_A],
__b: Observable[_B],
__c: Observable[_C],
__d: Observable[_D],
__e: Observable[_E],
) -> Observable[Tuple[_A, _B, _C, _D, _E]]:
...
def fork_join(*sources: Observable[Any]) -> Observable[Any]:
"""Wait for observables to complete and then combine last values
they emitted into a tuple. Whenever any of that observables completes
without emitting any value, result sequence will complete at that moment as well.
.. marble::
:alt: fork_join
---a-----b--c---d-|
--1---2------3-4---|
-a---------b---|
[ fork_join() ]
--------------------d4b|
Examples:
>>> obs = reactivex.fork_join(obs1, obs2, obs3)
Args:
sources: Sequence of observables.
Returns:
An observable sequence containing the result of combining last element from
each source in given sequence.
"""
from .observable.forkjoin import fork_join_
return fork_join_(*sources)
def from_callable(
supplier: Callable[[], _T], scheduler: Optional[abc.SchedulerBase] = None
) -> Observable[_T]:
"""Returns an observable sequence that contains a single element generated
by the given supplier, using the specified scheduler to send out observer
messages.
.. marble::
:alt: from_callable
[ from_callable() ]
--1--|
Examples:
>>> res = reactivex.from_callable(lambda: calculate_value())
>>> res = reactivex.from_callable(lambda: 1 / 0) # emits an error
Args:
supplier: Function which is invoked to obtain the single element.
scheduler: [Optional] Scheduler instance to schedule the values on.
If not specified, the default is to use an instance of
:class:`CurrentThreadScheduler
<reactivex.scheduler.CurrentThreadScheduler>`.
Returns:
An observable sequence containing the single element obtained by
invoking the given supplier function.
"""
from .observable.returnvalue import from_callable_
return from_callable_(supplier, scheduler)
def from_callback(
func: Callable[..., Callable[..., None]],
mapper: Optional[typing.Mapper[Any, Any]] = None,
) -> Callable[[], Observable[Any]]:
"""Converts a callback function to an observable sequence.
Args:
func: Function with a callback as the last argument to
convert to an Observable sequence.
mapper: [Optional] A mapper which takes the arguments
from the callback to produce a single item to yield on
next.
Returns:
A function, when executed with the required arguments minus
the callback, produces an Observable sequence with a single
value of the arguments to the callback as a list.
"""
from .observable.fromcallback import from_callback_
return from_callback_(func, mapper)
def from_future(future: "Future[_T]") -> Observable[_T]:
"""Converts a Future to an Observable sequence
.. marble::
:alt: from_future
[ from_future() ]
------1|
Args:
future: A Python 3 compatible future.
https://docs.python.org/3/library/asyncio-task.html#future
Returns:
An observable sequence which wraps the existing future success
and failure.
"""
from .observable.fromfuture import from_future_
return from_future_(future)
def from_iterable(
iterable: Iterable[_T], scheduler: Optional[abc.SchedulerBase] = None
) -> Observable[_T]:
"""Converts an iterable to an observable sequence.
.. marble::
:alt: from_iterable
[ from_iterable(1,2,3) ]
---1--2--3--|
Example:
>>> reactivex.from_iterable([1,2,3])
Args:
iterable: An Iterable to change into an observable sequence.
scheduler: [Optional] Scheduler instance to schedule the values on.
If not specified, the default is to use an instance of
:class:`CurrentThreadScheduler
<reactivex.scheduler.CurrentThreadScheduler>`.
Returns:
The observable sequence whose elements are pulled from the
given iterable sequence.
"""
from .observable.fromiterable import from_iterable_ as from_iterable_
return from_iterable_(iterable, scheduler)
from_ = alias("from_", "Alias for :func:`reactivex.from_iterable`.", from_iterable)
from_list = alias(
"from_list", "Alias for :func:`reactivex.from_iterable`.", from_iterable
)
def from_marbles(
string: str,
timespan: typing.RelativeTime = 0.1,
scheduler: Optional[abc.SchedulerBase] = None,
lookup: Optional[Mapping[Union[str, float], Any]] = None,
error: Optional[Exception] = None,
) -> Observable[Any]:
"""Convert a marble diagram string to a cold observable sequence, using
an optional scheduler to enumerate the events.
.. marble::
:alt: from_marbles
[ from_marbles(-1-2-3-) ]
-1-2-3-|
Each character in the string will advance time by timespan
(except for space). Characters that are not special (see the table below)
will be interpreted as a value to be emitted. Numbers will be cast
to int or float.
Special characters:
+------------+--------------------------------------------------------+
| :code:`-` | advance time by timespan |
+------------+--------------------------------------------------------+
| :code:`#` | on_error() |
+------------+--------------------------------------------------------+
| :code:`|` | on_completed() |
+------------+--------------------------------------------------------+
| :code:`(` | open a group of marbles sharing the same timestamp |
+------------+--------------------------------------------------------+
| :code:`)` | close a group of marbles |
+------------+--------------------------------------------------------+
| :code:`,` | separate elements in a group |
+------------+--------------------------------------------------------+
| <space> | used to align multiple diagrams, does not advance time |
+------------+--------------------------------------------------------+
In a group of elements, the position of the initial :code:`(` determines the
timestamp at which grouped elements will be emitted.
E.g. :code:`--(12,3,4)--` will emit 12, 3, 4 at 2 * timespan and then
advance virtual time by 8 * timespan.
Examples:
>>> from_marbles('--1--(2,3)-4--|')
>>> from_marbles('a--b--c-', lookup={'a': 1, 'b': 2, 'c': 3})
>>> from_marbles('a--b---#', error=ValueError('foo'))
Args:
string: String with marble diagram
timespan: [Optional] Duration of each character in seconds.
If not specified, defaults to :code:`0.1`.
scheduler: [Optional] Scheduler to run the the input sequence
on. If not specified, defaults to the subscribe scheduler
if defined, else to an instance of
:class:`NewThreadScheduler <reactivex.scheduler.NewThreadScheduler`.
lookup: [Optional] A dict used to convert an element into a specified
value. If not specified, defaults to :code:`{}`.
error: [Optional] Exception that will be use in place of the :code:`#`
symbol. If not specified, defaults to :code:`Exception('error')`.
Returns:
The observable sequence whose elements are pulled from the
given marble diagram string.
"""
from .observable.marbles import from_marbles as _from_marbles
return _from_marbles(
string, timespan, lookup=lookup, error=error, scheduler=scheduler
)
cold = alias("cold", "Alias for :func:`reactivex.from_marbles`.", from_marbles)
def generate_with_relative_time(
initial_state: _TState,
condition: typing.Predicate[_TState],
iterate: typing.Mapper[_TState, _TState],
time_mapper: Callable[[_TState], typing.RelativeTime],
) -> Observable[_TState]:
"""Generates an observable sequence by iterating a state from an
initial state until the condition fails.
.. marble::
:alt: generate_with_relative_time
[generate_with_relative_time()]
-1-2-3-4-|
Example:
>>> res = reactivex.generate_with_relative_time(
0, lambda x: True, lambda x: x + 1, lambda x: 0.5
)
Args:
initial_state: Initial state.
condition: Condition to terminate generation (upon returning
:code:`False`).
iterate: Iteration step function.
time_mapper: Time mapper function to control the speed of
values being produced each iteration, returning relative times, i.e.
either a :class:`float` denoting seconds, or an instance of
:class:`timedelta`.
Returns:
The generated sequence.
"""
from .observable.generatewithrelativetime import generate_with_relative_time_
return generate_with_relative_time_(initial_state, condition, iterate, time_mapper)
def generate(
initial_state: _TState,
condition: typing.Predicate[_TState],
iterate: typing.Mapper[_TState, _TState],
) -> Observable[_TState]:
"""Generates an observable sequence by running a state-driven loop
producing the sequence's elements.
.. marble::
:alt: generate
[ generate() ]
-1-2-3-4-|
Example:
>>> res = reactivex.generate(0, lambda x: x < 10, lambda x: x + 1)
Args:
initial_state: Initial state.
condition: Condition to terminate generation (upon returning
:code:`False`).
iterate: Iteration step function.
Returns:
The generated sequence.
"""
from .observable.generate import generate_
return generate_(initial_state, condition, iterate)
def hot(
string: str,
timespan: typing.RelativeTime = 0.1,
duetime: typing.AbsoluteOrRelativeTime = 0.0,
scheduler: Optional[abc.SchedulerBase] = None,
lookup: Optional[Mapping[Union[str, float], Any]] = None,
error: Optional[Exception] = None,
) -> Observable[Any]:
"""Convert a marble diagram string to a hot observable sequence, using
an optional scheduler to enumerate the events.
.. marble::
:alt: hot
[ from_marbles(-1-2-3-) ]
-1-2-3-|
-2-3-|
Each character in the string will advance time by timespan
(except for space). Characters that are not special (see the table below)
will be interpreted as a value to be emitted. Numbers will be cast
to int or float.
Special characters:
+------------+--------------------------------------------------------+
| :code:`-` | advance time by timespan |
+------------+--------------------------------------------------------+
| :code:`#` | on_error() |
+------------+--------------------------------------------------------+
| :code:`|` | on_completed() |
+------------+--------------------------------------------------------+
| :code:`(` | open a group of elements sharing the same timestamp |
+------------+--------------------------------------------------------+
| :code:`)` | close a group of elements |
+------------+--------------------------------------------------------+
| :code:`,` | separate elements in a group |
+------------+--------------------------------------------------------+
| <space> | used to align multiple diagrams, does not advance time |
+------------+--------------------------------------------------------+
In a group of elements, the position of the initial :code:`(` determines the
timestamp at which grouped elements will be emitted.
E.g. :code:`--(12,3,4)--` will emit 12, 3, 4 at 2 * timespan and then
advance virtual time by 8 * timespan.
Examples:
>>> hot("--1--(2,3)-4--|")
>>> hot("a--b--c-", lookup={'a': 1, 'b': 2, 'c': 3})
>>> hot("a--b---#", error=ValueError("foo"))
Args:
string: String with marble diagram
timespan: [Optional] Duration of each character in seconds.
If not specified, defaults to :code:`0.1`.
duetime: [Optional] Absolute datetime or timedelta from now that
determines when to start the emission of elements.
scheduler: [Optional] Scheduler to run the the input sequence
on. If not specified, defaults to an instance of
:class:`NewThreadScheduler <reactivex.scheduler.NewThreadScheduler>`.
lookup: [Optional] A dict used to convert an element into a specified
value. If not specified, defaults to :code:`{}`.
error: [Optional] Exception that will be use in place of the :code:`#`
symbol. If not specified, defaults to :code:`Exception('error')`.
Returns:
The observable sequence whose elements are pulled from the
given marble diagram string.
"""
from .observable.marbles import hot as _hot
return _hot(
string, timespan, duetime, lookup=lookup, error=error, scheduler=scheduler
)
def if_then(
condition: Callable[[], bool],
then_source: Union[Observable[_T], "Future[_T]"],
else_source: Union[None, Observable[_T], "Future[_T]"] = None,
) -> Observable[_T]:
"""Determines whether an observable collection contains values.
.. marble::
:alt: if_then
---1--2--3--|
--6--8--|
[ if_then() ]
---1--2--3--|
Examples:
>>> res = reactivex.if_then(condition, obs1)
>>> res = reactivex.if_then(condition, obs1, obs2)
Args:
condition: The condition which determines if the then_source or
else_source will be run.
then_source: The observable sequence or :class:`Future` that
will be run if the condition function returns :code:`True`.
else_source: [Optional] The observable sequence or :class:`Future`
that will be run if the condition function returns :code:`False`.
If this is not provided, it defaults to :func:`empty() <reactivex.empty>`.
Returns:
An observable sequence which is either the then_source or
else_source.
"""
from .observable.ifthen import if_then_
return if_then_(condition, then_source, else_source)
def interval(
period: typing.RelativeTime, scheduler: Optional[abc.SchedulerBase] = None
) -> Observable[int]:
"""Returns an observable sequence that produces a value after each period.
.. marble::
:alt: interval
[ interval() ]
---1---2---3---4--->
Example:
>>> res = reactivex.interval(1.0)
Args:
period: Period for producing the values in the resulting sequence
(specified as a :class:`float` denoting seconds or an instance of
:class:`timedelta`).
scheduler: Scheduler to run the interval on. If not specified, an
instance of :class:`TimeoutScheduler <reactivex.scheduler.TimeoutScheduler>`
is used.
Returns:
An observable sequence that produces a value after each period.
"""
from .observable.interval import interval_
return interval_(period, scheduler)
def merge(*sources: Observable[Any]) -> Observable[Any]:
"""Merges all the observable sequences into a single observable sequence.
.. marble::
:alt: merge
---1---2---3---4-|
-a---b---c---d--|
[ merge() ]
-a-1-b-2-c-3-d-4-|
Example:
>>> res = reactivex.merge(obs1, obs2, obs3)
Args:
sources: Sequence of observables.
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
from .observable.merge import merge_
return merge_(*sources)
def never() -> Observable[Any]:
"""Returns a non-terminating observable sequence, which can be used
to denote an infinite duration (e.g. when using reactive joins).
.. marble::
:alt: never
[ never() ]
-->
Returns:
An observable sequence whose observers will never get called.
"""
from .observable.never import never_
return never_()
def of(*args: _T) -> Observable[_T]:
"""This method creates a new observable sequence whose elements are taken
from the arguments.
.. marble::
:alt: of
[ of(1,2,3) ]
---1--2--3--|
Note:
This is just a wrapper for
:func:`reactivex.from_iterable(args) <reactivex.from_iterable>`
Example:
>>> res = reactivex.of(1,2,3)
Args:
args: The variable number elements to emit from the observable.
Returns:
The observable sequence whose elements are pulled from the
given arguments
"""
return from_iterable(args)
def on_error_resume_next(
*sources: Union[
Observable[_T], "Future[_T]", Callable[[Optional[Exception]], Observable[_T]]
]
) -> Observable[_T]:
"""Continues an observable sequence that is terminated normally or
by an exception with the next observable sequence.
.. marble::
:alt: on_error_resume_next
--1--2--*
a--3--4--*
b--6-|
[on_error_resume_next(a,b)]
--1--2----3--4----6-|
Examples:
>>> res = reactivex.on_error_resume_next(xs, ys, zs)
Args:
sources: Sequence of sources, each of which is expected to be an
instance of either :class:`Observable` or :class:`Future`.
Returns:
An observable sequence that concatenates the source sequences,
even if a sequence terminates with an exception.
"""
from .observable.onerrorresumenext import on_error_resume_next_
return on_error_resume_next_(*sources)
def range(
start: int,
stop: Optional[int] = None,
step: Optional[int] = None,
scheduler: Optional[abc.SchedulerBase] = None,
) -> Observable[int]:
"""Generates an observable sequence of integral numbers within a
specified range, using the specified scheduler to send out observer
messages.
.. marble::
:alt: range
[ range(4) ]
--0--1--2--3--|
Examples:
>>> res = reactivex.range(10)
>>> res = reactivex.range(0, 10)
>>> res = reactivex.range(0, 10, 1)
Args:
start: The value of the first integer in the sequence.
stop: [Optional] Generate number up to (exclusive) the stop
value. Default is `sys.maxsize`.
step: [Optional] The step to be used (default is 1).
scheduler: [Optional] The scheduler to schedule the values on.
If not specified, the default is to use an instance of
:class:`CurrentThreadScheduler
<reactivex.scheduler.CurrentThreadScheduler>`.
Returns:
An observable sequence that contains a range of sequential
integral numbers.
"""
from .observable.range import range_
return range_(start, stop, step, scheduler)
def return_value(
value: _T, scheduler: Optional[abc.SchedulerBase] = None
) -> Observable[_T]:
"""Returns an observable sequence that contains a single element,
using the specified scheduler to send out observer messages.
There is an alias called 'just'.
.. marble::