android / android-ktx

A set of Kotlin extensions for Android app development.
https://android.github.io/android-ktx/core-ktx/
7.48k stars 565 forks source link

View.post with with this view as a parameter #586

Closed romtsn closed 6 years ago

romtsn commented 6 years ago

Sometimes it's tedious to call a post method on some View object, and then access this object again inside the braces, especially with databinding. For example:

binding.included.toolbar.post {
    binding.included.toolbar.subtitle = "something"
}

If we'd have a following extension, it could make it a little bit easier:

inline fun <reified T : View> T.postOnView(crossinline action: (T) -> Unit): Runnable

// usage
binding.included.toolbar.postOnView { it.subtitle = "something" }
JakeWharton commented 6 years ago

My general problem with this is that the majority of APIs accepting some kind of callback or lambda do not provide the enclosing instance and we would have to apply this trick to all of them.

The traditional Kotlin pattern for solving this is to create a scope with the instance you want to re-use with let:

binding.included.toolbar.let { toolbar ->
  toolbar.post { toolbar.subtitle = "something" }
}
romtsn commented 6 years ago

Good point, also with is a good candidate for this. Just thought that the post is the most usable thing, which could've had such an extension to ease the usage for those, who is not aware of scoping functions/doesn't want to use them for reasons.