Search code examples
iosswiftreactive-swift

Skip(while:) call against a Signal in ReactiveSwift is being ignored


I have an observer against a Signal that is producing an item count in my app. Ideally, I would like to skip all values of 0, which I have attempted to do using the following code snippet:

viewModel.itemCount.signal
    .skipRepeats()
    .skip(while: { itemCount -> Bool in return itemCount == 0 })
    .observeValues { itemCount in
        print("Item count: \(itemCount)") // Will still print 0
}

Unfortunately, it is still allowing a value of 0 to pass through.


Solution

  • So my approach was incorrect, as skip(while:) is only applied upon the start of the signal. Since the initial value satisfied its criteria, the signal was allowed to continue and the skip(while:) check was ignored going forward.

    The correct call is the filter(:) command, as seen here:

    .filter({ itemCount -> Bool in return itemCount != 0 })
    

    Using filter does not affect the signal, focusing instead on whether or not you should observe the value passed along.