Florian
12/17/2020, 7:58 AMflatMapLatest
that I can trigger explicitly and only once? I want to switch a Flow to another Flow if a certain condition is metbezrukov
12/17/2020, 8:49 AMfirstFlow.filter { condition }.take(1).flatMapLatest { secondFlow }
Florian
12/17/2020, 9:09 AMinit
blockGiorgos Neokleous
12/17/2020, 9:15 AMwasyl
12/17/2020, 10:10 AM@Test
fun `switching flows`() {
val condition = MutableStateFlow(false)
val firstFlow = flow {
var i = 0
while (true) {
emit("original: ${i++}")
delay(10)
}
}
val secondFlow = flow {
var i = 0
while (true) {
emit("modified: ${i++}")
delay(10)
}
}
runBlocking {
val job = launch {
condition
.flatMapLatest { switched -> if (switched) secondFlow else firstFlow }
.collect { println(it) }
}
delay(100)
condition.value = true
delay(200)
job.cancel()
}
}
Florian
12/17/2020, 5:27 PMprivate val chatMessagesHistoryFlow = chat.asFlow()
.flatMapLatest { chat ->
chat?.let {
chatRepository.getChatMessagesHistory(it).cachedIn(viewModelScope)
} ?: emptyFlow()
}.catch { t ->
showErrorMessage(t.localizedMessage ?: "Message couldn't be loaded")
emit(PagingData.empty())
}
init
blockinit
block?viewModelScope.launch {
searchingForExistingDirectChat?.join()
chat.value?.let { chat ->
chatRepository.getChatMessagesHistory(chat).cachedIn(viewModelScope)
.catch { t ->
showErrorMessage(t.localizedMessage ?: "Messages couldn't be loaded")
emit(PagingData.empty())
}
.collect {
chatMessagesHistoryChannel.send(it)
}
}
}
Does this make sense?