当我从ViewModel的 Activity 中调用api时,我正在使用MVVM模式,它总是抛出错误

Smart cast to 'MainActivityViewModel' is impossible, because 'binding.mainModel' is a complex expression

以下是我的ViewMode:
class MainActivityViewModel(private val api: SearchAPI) : BaseViewModel() {

private var query: String = ""
    get() = if (field.isEmpty()) "MVVM" else field

private val _refreshing: NotNullMutableLiveData<Boolean> = NotNullMutableLiveData(false)
val refreshing: NotNullMutableLiveData<Boolean>
    get() = _refreshing

lateinit var  _items: NotNullMutableLiveData<RetrofitWrapper>
val items: NotNullMutableLiveData<RetrofitWrapper>
    get() = _items

fun getMainPageData() {
    val params = mutableMapOf<String, String>().apply {
        this["version"] = "v1"
        this["locale"] = "en"
        this["platform"] = "android"
    }

    addToDisposable(api.getHomePageDetail(params).with()
        .doOnSubscribe { _refreshing.value = true }
        .doOnSuccess { _refreshing.value = false }
        .doOnError { _refreshing.value = false }
        .subscribe({
            _items.value = it
        }, {
            // handle errors
        })
    )
}

}

以下是我的MainActivity:
class MainActivity : BindingActivity<ActivityMain2Binding>() {
    override fun getLayoutResId(): Int {
        return R.layout.activity_main2
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.mainModel = getViewModel()
        binding.setLifecycleOwner(this)
        binding.mainModel.getMainPageData()

    }
    }

非常感谢您在此问题上的帮助,请告诉我为什么会这样。

最佳答案

binding.mainModel是一个可变的,可为空的变量。

生成的绑定(bind) setter 方法代码将如下所示:
public void setViewModel(@Nullable MainActivityViewModel viewModel) { ... }
当您调用binding.mainModel.getMainPageData()时,无法推断该变量不为null。

您可以:
binding.mainModel!!.getMainPageData()
或更安全地:
binding.mainModel?.getMainPageData()

08-26 08:22