https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

Lokik Soni

02/20/2022, 4:23 PM
Hi all, Is it possible to use cold flow builder with Broadcast receiver. Currently I am doing my job with the help of hot flow MutableSharedFlow. But I do not want to use it*.* To see full code see in thread.
Copy code
abstract class BaseBroadcastReceiver<T>(
    private val _ctx: Context,
    private val _filter: IntentFilter,
    private val _scope: CoroutineScope
): BroadcastReceiver(), DefaultLifecycleObserver {

    protected val dataSharedFlow = MutableSharedFlow<T>()
    var dataFlow: SharedFlow<T> = dataSharedFlow

    override fun onReceive(context: Context?, intent: Intent?) {

        context?.let { ctx ->

            intent?.let { intent ->
                
                // TODO check for correct dispatcher
                _scope.launch(Dispatchers.Default) {
                    listen(
                        context = ctx,
                        intent = intent
                    )
                }

            } ?: TimberUtils.error("BroadcastReceiver onReceive Intent is NULL")

        } ?: TimberUtils.error("BroadcastReceiver onReceive Context is NULL")
    }

    abstract suspend fun listen(context: Context, intent: Intent)

    override fun onStart(owner: LifecycleOwner) {
        TimberUtils.debug("registerReceiver called.")

        // Register the broadcastReceiver
        _ctx.registerReceiver(this, _filter)
    }

    override fun onStop(owner: LifecycleOwner) {
        TimberUtils.debug("unregisterReceiver called.")

        // Unregister the broadcastReceiver
        _ctx.unregisterReceiver(this)
    }
}
Copy code
@Singleton
class BatteryBroadcast(
    context: Context,
    filter: IntentFilter,
    externalScope: CoroutineScope,
): BaseBroadcastReceiver<IBatteryProfile>(context, filter, externalScope) {

    companion object {
        const val DEF_VAL = -1
    }

    override suspend fun listen(context: Context, intent: Intent) {

        intent.apply {
            dataSharedFlow.emit(
                BatteryProfile(
                    context,
                    technology = getStringExtra(EXTRA_TECHNOLOGY),
                    _level = getIntExtra(EXTRA_LEVEL, DEF_VAL),
                    _voltage =  getIntExtra(EXTRA_VOLTAGE, DEF_VAL),
                    _temperature = getIntExtra(EXTRA_TEMPERATURE, DEF_VAL),
                    _status = getIntExtra(EXTRA_STATUS, DEF_VAL),
                    _plugged = getIntExtra(EXTRA_PLUGGED, DEF_VAL),
                    _health = getIntExtra(EXTRA_HEALTH, DEF_VAL),
                )
            )
        }
    }
}
n

Nick Allen

02/21/2022, 12:26 AM
See
callbackFlow
30 Views