android - 使用 RxJava 避免 Thread.sleep

标签 android rx-android

我对这个方法应用了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/

相关文章:

android - 无法从 index.android.bundle 中找到 setTimeOut

android - 如何实现半透明StatusBar和ActionBar的无缝过渡?

android - MissingBackpressureException 甚至添加了 .onBackpressureDrop()?

android - 使用 RxAndroid,从网络接收数据后,我应该在哪里(用哪种方法)调用数据库中的数据插入部分?

Android:在for循环中调用Observer并返回值

java - 如何按字母顺序对 Arraylist 进行排序? ( java )

android - Cocos2D 示例中的 NoClassDefFoundError

android - Android 3.1 中的 BootupReceiver

android - 在 Kotlin for Android 中编程时使用 RxAndroid 或 RxKotlin?

rx-java - 如何以线性方式连接两个可观察的操作(先做这件事,然后做第二件事)?