Hello! I have MutableStateFlow (with string data a...
# flow
s
Hello! I have MutableStateFlow (with string data as state) in PhoneStateListener class. I want to collect this flow in another class, where listener provides in constructor (repository). But this works only first time.
Copy code
private val _state = MutableStateFlow("initial")
val state: StateFlow<String> = _state
How i change state:
Copy code
_state.value = "ringing"
How collected:
Copy code
fun getCallLog() = flow<String> {
    listenerService.state.collect {
        Log.d("CALL STATE", it)
        emit(it)
    }
}
When I collect in the same place where I create StateFlow all works fine.
b
So you should make your state flow immutable in your ListenerService as such:
val state: StateFlow<String> = _state.asStateFlow()
Then, instead of wrapping the state flow, you can just pass it back directly when you call
getCallLog()
. Each time you collect the flow, it'll emit the latest item as well as all subsequent ones.
If you want to keep your debug log, you can do:
Copy code
fun getCallLog(): Flow<String> = listenerService.state.onEach { Log.d("CALL STATE", it) }
s
Thanks! It work!