Home > Enterprise >  Kotlin flow map - make emit even if the value is same
Kotlin flow map - make emit even if the value is same

Time:07-26

I want to know the kotlin flow flatMap working with jetpack compose

I am having a flow for search and i am calling the api each time the search value changes.

var search = MutableStateFlow("")

And to call api

var allItems = search.flatMapLatest{query->
  flow{
           emit(repository.getAllItems(query)
    }
}

It works perfectly fine , but excpet in one scenario. When the value of search is already "" an empty string, and i try to refresh the page , the code inside flatmap is not working as the search value is already and empty string and to refresh i try again hit the api call by just changing search value to "" inorder to triger the api call written inside fla map. So What can be done to make this flatmap work even if the search value is same .

CodePudding user response:

Use SharedFlow instead of StateFlow, because StateFlow behaves performing distinctUntilChanged() by default

reference: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/distinct-until-changed.html

  • Related