Imagine following scenario:
I open Search View and SearchViewModel
is initialized
class SearchViewModel(
usecase: Usecase
) : ViewModel() {
init {
viewModelScope.launch {
usecase.initialize()
}
}
fun search(query: String) = viewModelScope.launch {
usecase.search(query)
}
}
User start typing characters calling search
class UseCase(
private val dataSource: DataSource
private val store: Store
) {
private val searchQueryEmitter = MutableStateFlow<String>("") // 2 change to MutableSharedFlow
private val searchQuery = searchQueryEmitter
.mapLatest { query -> dataSource.search(query) }
.onEach { store.update(it) }
.launchIn(CoroutineScope(Dispatchers.Default)) // 1 comment
suspend fun search(query: String) {
searchQueryEmitter.emit(query)
}
override suspend fun initialize() {
// searchQuery.launchIn(CoroutineScope(Dispatchers.Default)) // > Emit only initial value
// searchQuery.collect() // > Emit only initial value
}
}
Flow emits first item ""
and next items according to query
value
PROBLEM:
- I don't understand if we comment
launchIn
(1), and call it later ininitialize()
method, then exactly the samesearchQuery.launchIn(...)
orsearchQuery.collect()
cause issue - flow emits only first item""
, but callingsearch
withquery
doesn't trigger emission of next items. - If we change
StateFlow
toSharedFlow
no items will be emitted in any case.