https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

Ben

05/06/2021, 7:38 PM
I'm looking to re-emit the last search result when refresh() is called. What I have below works, but is there a nicer way of doing it? (More specifically, I found the apply block for the refreshChannel was necessary for the resultStream to emit at all, but it doesn't feel right).
Copy code
private val searchQueryStream = MutableStateFlow<String>("")

private val refreshChannel = Channel<Unit>(Channel.CONFLATED).apply { offer(Unit) }

val resultStream: Flow<PagingData<TenorGifTileData>> =
    searchQueryStream
        .combine(refreshChannel.receiveAsFlow()) { queryStream, _ -> queryStream }
        .filter { searchQuery ->
            searchQuery.query.isNotEmpty()
        }
        .flatMapLatest { searchQuery ->
            repository.resultsForSearchQuery(searchQuery)
        }

fun refresh() {
    if (!refreshChannel.isClosedForSend) {
        refreshChannel.offer(Unit)
    }
}
u

ursus

05/07/2021, 12:06 PM
I'd turn the refresh trigger into a MutableSharedFlow with a starting value and on refresh just emit Unit into it
❤️ 1
2 Views