manueldidonna
11/15/2020, 6:17 PMvar result by remember { mutableStateOf(emptyList<String>()) }
val (query, changeQuery) = remember { mutableStateOf("") }
LaunchedEffect(subject = query) {
delay(300L)
stations = getResultFromWebServer(query)
}
BasicTextField(value = query, onValueChange = changeQuery)
Is this the correct way to do it?zoha131
11/15/2020, 6:27 PMgetResultFromWebServer
should be ViewModel’s responsibility. You can use StateFlow
on viewModel
and observe that on init
block to fire the rest api call.
class MyViewModel: ViewModel() {
private val _query = MutableStateFlow("")
val query: StateFlow<String> get() = _query
init {
viewModelScope.launch {
query.debounce(300).drop(1).collect { key ->
getResultFromWebServer(key)
}
}
}
}
Timo Drick
11/15/2020, 6:27 PMmanueldidonna
11/15/2020, 6:33 PMgetResultFromWebServer
is a name chosen to better explain my request, it's a simple callback that calls a viewmodel function. My doubt was around the debouncing mechanism. Who has that responsability? The viewmodel?
Is this ok?
class MyViewModel : ViewModel() {
private val query = MutableStateFlow("")
fun searchByQuery(query: String) {
this.query.value = query
}
fun observeResult(): Flow<List<String>> {
return query.debounce(300L).drop(1).map { getResultFromWebServer(it) }
}
}
@Timo Drick to skip the search when the text changes too fast, yes.Timo Drick
11/15/2020, 6:37 PMmanueldidonna
11/15/2020, 6:39 PMKshitij Patil
12/07/2020, 11:21 AMmanueldidonna
12/07/2020, 12:31 PM// query is the subject of the effect
LaunchedEffect(query) {
// the coroutine is delayed by 400ms
// if in the meantime query changes
// the coroutine is cancelled and callToTheServer is never invoked
delay(400)
callToTheServer(query)
}
Kshitij Patil
12/07/2020, 12:33 PM