0

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?

Sergio
  • 27,326
  • 8
  • 128
  • 149
Mohammad Mirdar
  • 56
  • 1
  • 11

1 Answers1

5

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(...)

    }
}
Sergio
  • 27,326
  • 8
  • 128
  • 149
  • 2
    Thank you! your answer helped me. but in another class that I collect, it collects data but does not goes to the next line. – Mohammad Mirdar May 24 '22 at 09:52
  • Probably because a new flow is being created each time `sendRequest` is called. Existing collectors will still be collecting from the old flow. – Tenfour04 May 24 '22 at 12:35
  • Right, maybe no need to create an instance of the flow each request. I've edited my answer. – Sergio May 24 '22 at 13:08
  • 3
    @BigSt your first answer was correct. I want to have an individual flow object for each requestWrapper object. I solved my issue with takeWhile operator before collecting the response. This approach helped me to cancel the collect and go to the next line. – Mohammad Mirdar May 24 '22 at 13:48