The takeWhile operator

Like filter, takeWhile also applies a predicate to elements emitted from observable sequences. However, takeWhile will terminate the sequence after the first time the specified condition is false, and all the remaining emitted element will be ignored. Think of takeWhile as a gate; once the gate is closed, nothing else gets through:

Let's make our playground ready for the implementation of takeWhile in a manner similar to what we did for all the other operators. Comment out all the previous implementations, create a bare-bones function implementation, and declare a disposeBag instance:

// Implementation for takeWhile operator
executeProcedure(for: "takeWhile") {
let disposeBag = DisposeBag()

}

Next, we will add an observable sequence of integers:

executeProcedure(for: "takeWhile") { 
let disposeBag = DisposeBag()

let integers = Observable.of(10, 20, 30, 40, 30, 20, 10)
}

Now we will use takeWhile, but note that there are several additional take operators:

We will use takeWhile for now, while the value is less than 40:

integers
.takeWhile({
$0 < 40
})

Then, we will subscribe and print out those elements:

integers
.takeWhile({
$0 < 40
})
.subscribe(onNext: {
print( $0 )
})

Note the output printed in the console:

Only elements up to the failed test are tested. Don't forget to dispose the subscriptions once again. The overall completed code for this implementation is as follows:

// Implementation for takeWhile operator
executeProcedure(for: "takeWhile") {
let disposeBag = DisposeBag()

let integers = Observable.of(10, 20, 30, 40, 30, 20, 10)
integers
.takeWhile({
$0 < 40
})
.subscribe(onNext: {
print( $0 ) .disposed(by: disposeBag)
}

We discussed a few of the most most used filtering operators in this chapter that you can use with RxSwift, but there are more. You can check them out as the need arises.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset