Clament John
11/10/2021, 10:21 AMmessages
from two flows (using flatMapLatest)
private val searchString = MutableStateFlow<String>("")
private val messages = searchString.flatMapLatest {
if (it == "") {
getAll()
} else {
search(it)
}
}.stateIn(viewModelScope, SharingStarted.Eagerly, null)
suspend fun requestSearch(search: String) = searchString.emit(search)
suspend fun requestAll() = searchString.emit("")
fun getAll(): Flow<List<Message>> = TODO()
fun search(search: String): Flow<List<Message>> = TODO()
But when I try emit
to update searchString
it doesn't work. Note: The initial condition of ""
was successfully executed.Joffrey
11/10/2021, 10:23 AMmessages
?Joffrey
11/10/2021, 10:25 AMstateIn
for messages
seems a bit strange, as messages feel more like a stream of things than a state. The consequence of using something meant for state is that if you have twice the same message, it won't trigger events in the consumersClament John
11/10/2021, 10:25 AMcollectAsState
in a composable.
I've set a breakpoint inside flatMapLatest
to see if it is getting triggered. But that break point was never hitClament John
11/10/2021, 10:26 AMmessages
to be consumed at a composable. So I added a stateIn
to convert it to a StateFlow, so that I can use collectAsState
. How do you think I should do it so that the Flow
from messages is consumed at the composableJoffrey
11/10/2021, 10:29 AMClament John
11/10/2021, 10:29 AMJoffrey
11/10/2021, 10:30 AMmessages
was a flow of lists, not just simple messages. How can you provide ""
as initial value then? Does this code compile?Clament John
11/10/2021, 10:31 AMnull
. Edited the code snippetJoffrey
11/10/2021, 10:32 AMrequestSearch
and requestAll
are not supposed to use emit()
, you should just set the value of the flow via its value
property:
fun requestSearch(search: String) {
searchString.value = search
}
fun requestAll() {
searchString.value = ""
}
Clament John
11/10/2021, 10:33 AMsearchString.value = ""
But this doesn't work eitherJoffrey
11/10/2021, 10:36 AMrequestSearch
, right? Because trying to send ""
will not trigger events of the searchString
flow if its last value was already ""
(it only triggers when the new value is not equal to the current state)Clament John
11/10/2021, 10:37 AMrequestSearch
to check if search was a non empty valueClament John
11/10/2021, 10:46 AMflatmapLatest
is working (but my breakpoints did not work for some reason). My current problem is not related to this anymore.
It is related to channelFlow
and me getting a ClosedChannelException
. Will ask a different question for that.Joffrey
11/10/2021, 10:47 AM