https://kotlinlang.org logo
#compose
Title
# compose
n

Nat Strangerweather

12/17/2021, 4:06 PM
Hi, I followed a YT tutorial to fetch some data through retrofit. I think I understood most of the tutorial and in fact everything works well. The only problem is that it requests live data and I don't need that. The api is complaining that there are too many calls. Do you have any idea how I can modify the code so that it only loads one time per query rather than continuously? 🧵
Copy code
class MainViewModel : ViewModel() {

    private val _repoQuery = MutableLiveData<String>()

    fun addQuery(query: String) {
        _repoQuery.value = query
    }

    val repoQuery = _repoQuery.switchMap {
        liveData {
            emit(Repo.getResults(it))
        }
    }
}
a

Adam Powell

12/17/2021, 4:14 PM
as written there isn't anything continuous there. If you're doing something like changing the query for every character typed, yeah you'll probably want to debounce that somewhere to stay within whatever the quota limits of your remote api are
n

Nat Strangerweather

12/17/2021, 4:16 PM
oh really, right, I'm obviously doing something wrong elsewhere. Thanks, that helps!
a

Adam Powell

12/17/2021, 4:20 PM
one easy way to do that debouncing would be to stick a
delay(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.
it defaults to 5 seconds of staying active in case a new observer comes back in that timeframe, kind of like `SharingStarted.WhileSubscribed`'s timeouts for flows (but flows don't have a nonzero default for that)
n

Nat Strangerweather

12/17/2021, 4:23 PM
I don't think the problem is when the query is being typed. I can see the list changing on its own when I am not touching anything and then the app crashes because of too many queries.
my composable looks like this:
Copy code
@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)
                }
            }
        }
    }
}
Hmm, it's not doing it anymore, weird. Thanks for the explanation in any case! 😊
2 Views