Reputation: 16691
I have a BaseObservable
that I use in databinding to display a network state. In this class, I pass in a retry callback that I want to run any time a button is clicked:
class NetworkStateViewModel(val retryCallback: () -> Unit) : BaseObservable() {
var networkState: NetworkState? = null
set(value) {
field = value
notifyChange()
}
val isLoading: Boolean
@Bindable get() = networkState is NetworkState.Loading
val isShowingError: Boolean
@Bindable get() = networkState is NetworkState.Error
val errorText: String
@Bindable get() = (networkState as? NetworkState.Error)?.error?.message.orEmpty()
}
However, when I try to reference retryCallback
through data binding, it can't compile as it says it's cannot find method retryCallback() in class NetworkStateViewModel
.
<Button
...
android:onClick="@{() -> viewModel.retryCallback()}"
... />
I have found one work around so far, which I'll post separately as an answer, but I'd like to know if I can call this directly.
Upvotes: 1
Views: 1599
Reputation: 1894
Just call invoke
method of lambda:
<Button
...
android:onClick="@{() -> viewModel.retryCallback.invoke()}"
... />
Upvotes: 6
Reputation: 16691
One work around to this is to not call the function type directly, but instead write a function that does so:
class NetworkStateViewModel(private val retryCallback: () -> Unit) : BaseObservable() {
...
fun retry() {
retryCallback()
}
...
}
And in XML:
<Button
...
android:onClick="@{() -> viewModel.retry()}"
... />
Upvotes: 0