android-ktx icon indicating copy to clipboard operation
android-ktx copied to clipboard

Best-practice for dealing with multi-callback listeners

Open simonschiller opened this issue 6 years ago • 3 comments

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 ... */ }

simonschiller avatar Apr 16 '18 14:04 simonschiller

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.

simonschiller avatar Apr 30 '18 06:04 simonschiller

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.

JakeWharton avatar Apr 30 '18 13:04 JakeWharton

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.

simonschiller avatar Apr 30 '18 14:04 simonschiller