android-ktx
android-ktx copied to clipboard
Best-practice for dealing with multi-callback listeners
As @JakeWharton mentioned here, we should define a common pattern for dealing with multi-callback listeners. There are many cases where this problem occurs (e.g. #382 or #351) and having a best-practice in place would help.
Take TextView.addTextChangedListener
for example. The API could look like this
textView.addTextChangedListener(
on = { /* Handle changes ... */ },
after = { /* Handle changes ... */ }
)
with empty defaults for unused listeners. Another option would be to add a function for every listener:
textView.onTextChanged { /* Handle changes ... */ }
textView.afterTextChanged { /* Handle changes ... */ }
I guess one advantage of my second proposed option is, that we are able to remove individual listeners:
val onWatcher = textView.onTextChanged { /* Handle changes ... */ }
val afterWatcher = textView.afterTextChanged { /* Handle changes ... */ }
textView.removeTextChangedListener(afterWatcher)
This would not be possible (or at least not reasonable) with the first approach.
I don't think that's a use case we care about optimizing for. For the first style, in the exceedingly rare case that you want to remove only a single callback you would just invoke the function twice.
You are right, I did not think about that. I guess in that case the first option would be preferable, as it would only create one TextWatcher
, whereas the second one would create two.