编程语言
首页 > 编程语言> > android-避免使用RxJava的Thread.sleep

android-避免使用RxJava的Thread.sleep

作者:互联网

我将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()中忽略可观察的内容.

像这样返回布尔值:

//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:您应该只注册一次接收器

intent = context.registerReceiver(broadCastReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))

标签:rx-android,android
来源: https://codeday.me/bug/20191025/1925752.html