Search code examples
androidkotlinkotlin-coroutineskotlin-flowkotlin-sharedflow

how to emit value from built flow object


My question is that how we can emit a value from a built flow object like this:

class Sample {
    var flow: Flow<Object> = null

    fun sendRequest(){
       flow = flow{}
       requestWrapper.flowResponse = flow

    }

    fun getResponse(){
       // I want to emit data here with built flow object on 
       // requestWrapper like this

        requestWrapper.flowResponse.emit()

    }
}

is any possible solution for this issue?


Solution

  • You can use MutableSharedFlow to emit values like in your case:

    class Sample {
        var flow: MutableSharedFlow<Object>? = MutableSharedFlow(...)
    
        fun sendRequest(){
           requestWrapper.flowResponse = flow
        }
    
        fun getResponse(){
           // I want to emit data here with built flow object on 
           // requestWrapper like this
    
            requestWrapper.flowResponse?.tryEmit(...)
    
        }
    }