我对这个方法应用了observable,但是在调用这个方法之后,它说主线程上的工作太多了。感谢任何帮助
fun isBatteryHealthGood(): Observable<Boolean> {
var count = 0
intent = context.registerReceiver(broadCastReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
while (batteryStatus == null && count < maxCount) {
Thread.sleep(1000)
count++
}
return Observable.just(batteryStatus == BatteryManager.BATTERY_HEALTH_GOOD)
}
最佳答案
我的解决方案是通过使用 interval operator 来避免使用 Thread.sleep() 我认为您可以在 isBatteryHealthGood() 中省略 observable。
像这样返回 bool 值:
//a simple function works here, no need
fun isBatteryHealthGood(): Boolean {
return batteryStatus == BatteryManager.BATTERY_HEALTH_GOOD
}
最后像这样订阅:
Observable.
interval(1000, TimeUnit.MILLISECONDS)
take(maxCount) //place max count here
.map { _ -> isBatteryHealthGood() }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.maintThread())
.subscribe {
batterystat ->
//do what you need
}
PS:你应该只注册一次receiver
intent = context.registerReceiver(broadCastReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
关于android - 使用 RxJava 避免 Thread.sleep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51374410/