Exemplo n.º 1
0
def first_or_default_(
    predicate: Optional[Predicate[_T]] = None,
    default_value: Optional[_T] = None
) -> Callable[[Observable[_T]], Observable[_T]]:
    """Returns the first element of an observable sequence that
    satisfies the condition in the predicate, or a default value if no
    such element exists.

    Examples:
        >>> res = source.first_or_default()
        >>> res = source.first_or_default(lambda x: x > 3)
        >>> res = source.first_or_default(lambda x: x > 3, 0)
        >>> res = source.first_or_default(None, 0)

    Args:
        source -- Observable sequence.
        predicate -- [optional] A predicate function to evaluate for
            elements in the source sequence.
        default_value -- [Optional] The default value if no such element
            exists.  If not specified, defaults to None.

    Returns:
        A function that takes an observable source and reutrn an
        observable sequence containing the first element in the
        observable sequence that satisfies the condition in the
        predicate, or a default value if no such element exists.
    """

    if predicate:
        return compose(ops.filter(predicate),
                       ops.first_or_default(None, default_value))
    return first_or_default_async_(True, default_value)
Exemplo n.º 2
0
        def create():
            def predicate(x):
                if x < 4:
                    return False
                else:
                    raise Exception(ex)

            return xs.pipe(ops.first_or_default(predicate, 0))
Exemplo n.º 3
0
        def create():
            def predicate(x):
                return x % 2 == 1

            return xs.pipe(ops.first_or_default(predicate, 0))
Exemplo n.º 4
0
 def create():
     return xs.pipe(ops.first_or_default(None, 0))