我使用 lambda 来处理来自异步调用的回调。我想在调用方法之外定义回调以避免笨重的方法,但我似乎无法在 lambda 中使用早期返回,这使得代码不必要地难以阅读。
我尝试将 lambda 定义为变量,但在 lambda 内部返回不可行。
我试过在函数内定义 lambda 并返回,但在那里返回也不可行。
例如:
private fun onDataUpdated(): (Resource<List<Int>>) -> Unit = {
if (it.data.isNullOrEmpty()) {
// Handle no data callback and return early.
return@onDataUpdated // This is not allowed
}
// Handle the data update
}
}
Run Code Online (Sandbox Code Playgroud)
我也试过:
private val onDataUpdated: (Resource<List<Int>>) -> Unit = {
if (it.data.isNullOrEmpty()) {
// Handle no data callback and return early.
return // This is not allowed
}
// Handle the data update
} …Run Code Online (Sandbox Code Playgroud) 我目前正在使用绑定来使用 android 视图模型动态设置各种文本视图的文本。目前视图模型看起来像这样:
class MyViewModel(
resources: Resources,
remoteClientModel: Model = Model()
) : ObservableViewModel() {
init {
observe(remoteClientModel.liveData) {
notifyChange()
}
fun getTextViewTitle(): String = when {
someComplicatedExpression -> resources.getString(R.string.some_string, null)
else -> resources.getString(R.string.some_other_string)
}
}
Run Code Online (Sandbox Code Playgroud)
和 xml 布局:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="android.view.View"/>
<variable
name="viewModel"
type="my.app.signature.MyViewModel"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{viewModel.textViewTitle}"
android:textAlignment="center"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)
但是我想删除注入到视图模型中的“资源:资源”,因为资源与活动耦合。代码现在只返回字符串资源 ID:
fun getTextViewTitle(): Int = when {
someComplicatedExpression -> R.string.some_string
else -> R.string.some_other_string
}
Run Code Online (Sandbox Code Playgroud)
因此,我删除了活动依赖项。编译器认为这很好,但它在运行时崩溃并出现以下异常:android.content.res.Resources$NotFoundException: …