Nat Strangerweather
12/17/2021, 4:06 PMNat Strangerweather
12/17/2021, 4:07 PMclass MainViewModel : ViewModel() {
private val _repoQuery = MutableLiveData<String>()
fun addQuery(query: String) {
_repoQuery.value = query
}
val repoQuery = _repoQuery.switchMap {
liveData {
emit(Repo.getResults(it))
}
}
}
Adam Powell
12/17/2021, 4:14 PMNat Strangerweather
12/17/2021, 4:16 PMAdam Powell
12/17/2021, 4:20 PMdelay(timeout)
before the emit
inside the liveData {}
builder block, which would have the effect of waiting timeout
milliseconds before sending the query. Since switchMap
would end up cancelling the previous livedata work it would cancel the old delays as the user is typing quickly and never execute those queries. You would need to drop the default timeout of liveData{}
though: liveData(timeoutInMs = 0L) { ... }
etc.Adam Powell
12/17/2021, 4:22 PMNat Strangerweather
12/17/2021, 4:23 PMNat Strangerweather
12/17/2021, 4:25 PM@Composable
fun CallApi(mainViewModel: MainViewModel) {
val bookList by mainViewModel.repoQuery.observeAsState()
if (bookList == null) {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator()
}
} else {
LazyColumn() {
item {
for (item in bookList!!.items) {
Text(text = item.volumeInfo.title)
}
}
}
}
}
Nat Strangerweather
12/17/2021, 4:29 PM