The let operator allows us to use a function like an operator. It allows us to use a function that takes an observable as input and returns an observable into a chain of operators, in a seamless way. The following figure shows the workings of this let operator:
The prototype of this operator is the following one:
Observable.let(self, func, **kwargs)
The implementation of the let operator is simply a call to the func function with the self and kwargs arguments:
func(self, **kwargs)
So, the let operator basically makes func an operator that takes the input stream of the let operator as the input parameter, as well as the eventual keyword arguments provided to the let call. The let operator allows us to factorize some code and implement operators like functions. Here is an example of how to use it:
def add_and_multiply(numbers, add_value, multiply_by_value):
return numbers
.map(lambda i: i + add_value)
.map(lambda i: i * multiply_by_value)
numbers = Observable.from_([1, 2, 3])
numbers.let(add_and_multiply, add_value=1, multiply_by_value=2)
.subscribe(
on_next = lambda i: print("on_next {}".format(i)),
on_error = lambda e: print("on_error: {}".format(e)),
on_completed = lambda: print("on_completed")
)
The add_and_multiply function performs two operations on each item of the input observable, an addition followed by a multiplication. The use of the let operator allows us to insert these two operations into the chain of operators. In this example, the resulting operations are similar to moving the two map operators in place of the let operator. The result of this code is the following: