https://kotlinlang.org logo
Title
s

Sanendak

04/07/2021, 5:31 PM
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.
private val _state = MutableStateFlow("initial")
val state: StateFlow<String> = _state
How i change state:
_state.value = "ringing"
How collected:
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

baxter

04/07/2021, 5:46 PM
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:
fun getCallLog(): Flow<String> = listenerService.state.onEach { Log.d("CALL STATE", it) }
s

Sanendak

04/07/2021, 5:52 PM
Thanks! It work!