Daniel's working notes

Using .scan operator in RxSwift

In [[ RxSwfit ]] there’s scan operator that can be useful when you want to flip back and forth from two values

An use case for it is when you want to toggle some value from true or false, on or off, active or inactive and etc.

In my experience, combined with enum, you can use scan to easily toggle value and bind them to an object or UI.

Let’s say you want to have a boolean for a state that is triggered by button tap, here’s you can make use of scan

switchButton.rx.tap.scan(false) { lastState, newValue in 
	return !lastState
}
.subscribe(onNext: { value in 
	print("tap: \(value)")
})

// This will print 
tap: true
tap: false
tap: true
tap: false

And here’s you can use it with enum

// For example, we want to have a button that can make a product is available on our shop or not
// First, we define the enum state
enum ProductStatus: String {
  case available
  case unavailable
}

// Next we use scan in our button and toggle between that state
productStatusButton.rx.tap.scan(false) { lastStatus, _ -> ProductStatus in 
	return lastStatus == .available : .unavailable : .available                                   
}
.subscribe(onNext: { productStatus in
 	// do something with the value from scan
})

Linked Notes: