Tuesday 3 August 2021

Live data observer inside CoroutineWorker

I have an Worker that executed periodically. It connects to BLE device and syncs data from it. The connection is done by observers. doWork calling syncRides(). syncRides created an observeForever, and starts connections, when connection is established BleClient.runBleSync() called.

My concerns are the "observeForever" called every 15 min (minimal WorkManager time) and crerates observeForever that not removed. The thing is BleWorker does not have LifecycleOwner for creating "BleClient.connectionStatus.observe" instead of "BleClient.connectionStatus.observeForever". My question is should I be concerned of using observeForever and triggering it every 15 min. Or maybe you can suggest better option like adding and removing observer.

class BleWorker(appContext: Context, workerParams: WorkerParameters) : CoroutineWorker(appContext, workerParams) {

override suspend fun doWork(): Result {

    return try {
        try {
            RLog.d("Run work manager")
            syncRides()
            val output: Data = workDataOf("KEY_RESULT" to 1)
            Result.success(output)
        } catch (e: Exception) {
            RLog.d("exception in doWork ${e.message}")
            Result.failure()
        }
    } catch (e: Exception) {
        RLog.d("exception in doWork ${e.message}")
        Result.failure()
    }
}


private suspend fun syncRides() {

    GlobalScope.launch(Dispatchers.Main) {

        val bleDevice = SharedPreferenceHelper.getBleMac()
        if (bleDevice != null && BleClient.connectionStatus.value == BleClient.ConnectionStatus.NOT_CONNECTED) {
            BleClient.connect(bleDevice)
        }

        BleClient.connectionStatus.observeForever {
            RLog.d("Observing $it")

            when (it) {
                BleClient.ConnectionStatus.CONNECTED -> {
                    GlobalScope.launch(Dispatchers.IO) {
                        RLog.d("Running sync")
                        BleClient.runBleSync()
                    }
                }
                else -> {
                    RLog.d("No status")
                }
            }
        }
    }
}

BleClient:

 object BleClient {

 val connectionStatus = MutableLiveData(ConnectionStatus.NOT_CONNECTED)

 fun connect(mac: String) {
//do some magic         
 connectionStatus.postValue(ConnectionStatus.CONNECTED)
 }
}


from Live data observer inside CoroutineWorker

No comments:

Post a Comment