I needed a battery manager when developing my apps with Rx. And I started to write the manager. With the battery manager, you can stream data from your battery in a reactive manner. For example, by subscribing to the critical battery status of your battery, you can improve the user experience and reduce battery usage by changing the dark/light modes of your application. I wanted to share this library I developed with the community. My biggest motivation was that the community was very helpful and friendly. I hope useful.
- iOS 9.0+
- Xcode 11+
- Swift 5.1+
- RxSwift 5.1.1+
Add package into Project settings -> Swift Packages
Add RxBatteryManager dependency to your Podfile
# Podfile
use_frameworks!
# replace YOUR_TARGET_NAME with yours
target 'YOUR_TARGET_NAME' do
pod 'RxBatteryManager', '~> 1.0'
end
and run
$ pod install
import RxBatteryManager
let battery = Battery.monitor
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Monitoring Battery
Battery.monitor.start()
return true
}
battery.level
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] level in
guard let self = self else { return }
print(level)
}).disposed(by: disposeBag)
battery.state
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] state in
guard let self = self else { return }
switch state {
case .unknown:
print("unknown")
case .unplugged:
print("unplugged")
case .charging:
print("charging")
case .full:
print("full")
@unknown default:
fatalError()
}
}).disposed(by: disposeBag)
battery.isLowPowerMode
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] isLowPowerMode in
guard let self = self else { return }
print(isLowPowerMode)
}).disposed(by: disposeBag)
battery.isLowLevel
.observeOn(MainScheduler.instance)
.distinctUntilChanged()
.subscribe(onNext: { [weak self] isLowLevel in
guard let self = self else { return }
self.isLowBatteryLabel.text = "\(isLowLevel)"
}).disposed(by: disposeBag)
battery.isCriticalLevel
.observeOn(MainScheduler.instance)
.distinctUntilChanged()
.subscribe(onNext: { [weak self] isCriticalLevel in
guard let self = self else { return }
self.isCriticalBatteryLabel.text = "\(isCriticalLevel)"
}).disposed(by: disposeBag)
Note: I recommend you subscribe to Main Thread
RxBatteryManager is available under the MIT license. See the LICENSE file for more info. Copyright (c) RxSwiftCommunity