Mohan K
Mohan K

Reputation: 484

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?

Upvotes: 4

Views: 1268

Answers (1)

Sergio
Sergio

Reputation: 30655

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

Upvotes: 3

Related Questions