https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Andrew Ebling

02/19/2021, 9:52 AM
I’m new to coroutines and struggling to get my head around the conceptuals while trying to implement a debounce:
Copy code
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when(item.itemId) {
        R.id.refresh -> {
            flow {
                callbacks?.refreshAllTheThings()
            }.debounce(5000)
            return true
        }
        else -> {
            return super.onOptionsItemSelected(item)
        }
    }
}
...however I get the following compilation error:
Not enough information to infer type variable T
I’ve gone and looked at the implementation of
debounce()
but the examples in the comments suggest what I have above should be sufficient. Why does flow need type information if I just want to execute one line of code, at most, every 5 seconds?
w

wasyl

02/19/2021, 9:56 AM
Flow is a flow of values that you need to collect somehow. In your example the error is just a compiler error because you don’t emit anything from the flow you create: if you just do
flow<Unit> { }
it would be enough to compile
However, it still wouldn’t work as you expect, because creating a flow doesn’t do anything by itself without collecting it
Besides, if you want debounce, you need to have just one flow for multiple clicks. Here you’d be creating a separate flow for every click anyway. I’m not sure how to best implement this with a callback like this though, you’d probably need a channel to which you post click events, and have a debounce on that channel
Something like:
Copy code
val clicksChannel = BroadcastChannel<Unit>(1)

fun onOptionsItemSelected() {
  clicksChannel.offer(Unit) 
}

onCreate() {
  lifecycleScope.launchWhenCreated {
    clicksChannel
      .asFlow()
      .debounce(5000)
      .collect { refreshAllThings() }
  }
}
a

Andrew Ebling

02/19/2021, 10:19 AM
great - many thanks - getting close, but I now realise
debounce
is not the behaviour I’m looking for - more like
throttle
but seems coroutines doesn’t use this out of the box?
debounce
is waiting until the timeout before sending the first event
w

wasyl

02/19/2021, 10:26 AM
a

Andrew Ebling

02/19/2021, 10:26 AM
lol - just reading through the comments on that exact issue :smile
w

wasyl

02/19/2021, 10:27 AM
Maybe
sample
would help? Not sure
a

Andrew Ebling

02/19/2021, 10:35 AM
I think that’s done the trick - many thanks for your help! 👍
👍 1
Actually - I’ve learned a tonne with you guidance this morning - a whole load of conceptual stuff has fallen into place. I’m just one of those people who learns far more effectively through seeing working code than reading it all explained in-theory.
Thanks again for taking time out of your day
w

wasyl

02/19/2021, 12:25 PM
Sure, happy to help 🙂
2 Views