Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MutableSharedFlow in Android Service?

I want to use MutableSharedFlow in the Service class, but I'm not sure how to stop subscribing when Service ends. How to implement the MutableSharedFlow function in service or any other function available to listen to stream data?

like image 227
Zero Cool Avatar asked Oct 19 '25 10:10

Zero Cool


1 Answers

To use a Flow in an android Service class we need a CoroutineScope instance to handle launching coroutines and cancellations. Please see the following code with my comments:

class CoroutineService : Service() {
    private val scope = CoroutineScope(Dispatchers.IO)

    private val flow = MutableSharedFlow<String>(extraBufferCapacity = 64)

    override fun onCreate() {
        super.onCreate()
        // collect data emitted by the Flow
        flow.onEach {
            // Handle data
        }.launchIn(scope)
    }

    override fun onStartCommand(@Nullable intent: Intent?, flags: Int, startId: Int): Int {
        scope.launch {
            // retrieve data from Intent and send it to Flow
            val messageFromIntent = intent?.let { it.extras?.getString("KEY_MESSAGE")} ?: ""
            flow.emit(messageFromIntent)
        }
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder?  = null

    override fun onDestroy() {
        scope.cancel() // cancel CoroutineScope and all launched coroutines
    }
}
like image 107
Sergey Avatar answered Oct 20 '25 23:10

Sergey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!