简体   繁体   中英

Avoid Thread.sleep using RxJava

I applied observable to this method, but after calling this method, it is saying too much work on the main thread. Any help is appreciated

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)
}

My solution is to avoid usage of Thread.sleep() by using interval operator I think you can ommit observable in isBatteryHealthGood().

Just return boolean like this:

//a simple function works here, no need
fun isBatteryHealthGood(): Boolean {


    return batteryStatus == BatteryManager.BATTERY_HEALTH_GOOD
}

and finally subscribe like this:

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: you should register receiver only once

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

As you want to make an asynchronous method execution. You should consider using Observable.fromCallable() not Observable.just().

Here is detailed article https://medium.com/yammer-engineering/converting-callback-async-calls-to-rxjava-ebc68bde5831

There are multiple problems with your code. You'd be better off just using a library like RxBroadcastReceiver so you can just write:

fun isBatteryHealthGood(): Observable<Boolean> {
    return RxBroadcastReceivers
        .fromIntentFilter(context, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
        .map {
            it.getIntExtra(BatteryManager.EXTRA_HEALTH, 0) == BatteryManager.BATTERY_HEALTH_GOOD
        }
}

One big benefit is that you don't register the broadcast receiver yourself and don't need to handle broadcasts at all, that logic is contained in the library and is routed through the observable stream.

So there's no need for Thread.sleep or Observable.timer , which honestly defeats the whole purpose of using a broadcast receiver that is supposed to "push" the changes to you, instead of "pulling" them every second.

Lastly, when you dispose() the result of isBatteryHealthGood() , it will automatically unregister the broadcast receiver for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM