You need to enable JavaScript to run this app. Android 如何结合Retrofit、ViewModel与LiveData实现登录及解决改造报错
优惠活动
大模型
产品
解决方案
定价
更多

Android 如何结合Retrofit、ViewModel与LiveData实现登录及解决改造报错

Retrofit + ViewModel + LiveData 登录功能改造指南

核心改造原则

彻底拆分层级职责,避免网络逻辑、ViewModel、Activity三者的代码耦合——改造过程中出现的编译报错,90%来自跨层持有引用、没有抽离依赖导致的类型不匹配、实例化失败问题。

分步实现方案

  • 第一步:抽离Repository层,作为数据请求的唯一中转
    不要把Retrofit实例直接写在ViewModel或Activity里。用单例Repository持有Retrofit生成的登录接口Service,所有网络请求的发起、回调处理全部在Repository层完成,对外只返回包装了请求状态的LiveData,不直接暴露Retrofit的Call对象。
    参考实现代码:

    // 带状态的请求资源封装,自定义实现即可,无需引入第三方依赖
    data class Resource<T>(
        val status: Status,
        val data: T?,
        val message: String?
    ) {
        enum class Status { LOADING, SUCCESS, ERROR }
    
        companion object {
            fun <T> success(data: T?) = Resource(Status.SUCCESS, data, null)
            fun <T> error(msg: String, data: T?) = Resource(Status.ERROR, data, msg)
            fun <T> loading(data: T?) = Resource(Status.LOADING, data, msg = null)
        }
    }
    
    class LoginRepository private constructor(private val loginService: ApiService) {
        fun login(account: String, pwd: String): LiveData<Resource<LoginResponse>> {
            val result = MutableLiveData<Resource<LoginResponse>>()
            result.postValue(Resource.loading(null))
            loginService.login(account, pwd).enqueue(object : Callback<LoginResponse> {
                override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
                    result.postValue(Resource.success(response.body()))
                }
                override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
                    result.postValue(Resource.error(t.message ?: "网络请求失败", null))
                }
            })
            return result
        }
    
        companion object {
            @Volatile
            private var instance: LoginRepository? = null
            fun getInstance(loginService: ApiService) =
                instance ?: synchronized(this) {
                    instance ?: LoginRepository(loginService).also { instance = it }
                }
        }
    }
    
  • 第二步:编写无UI依赖的LoginViewModel,解决ViewModel环节的编译报错
    高频报错根因:

    • 直接在ViewModel构造函数传Activity上下文,导致系统无法通过ViewModelProvider实例化(系统要求ViewModel必须支持无参构造)
    • 没有单独编写Factory类,试图直接带参new ViewModel实例,触发类型不匹配
      正确实现:
    class LoginViewModel(
        application: Application,
        private val repository: LoginRepository
    ) : AndroidViewModel(application) {
        // 对外暴露不可变的LiveData,只在ViewModel内部修改值
        private val _loginState = MutableLiveData<Resource<LoginResponse>>()
        val loginState: LiveData<Resource<LoginResponse>> = _loginState
    
        fun startLogin(account: String, pwd: String) {
            // 前置参数校验,避免无效请求
            if (account.isBlank() || pwd.isBlank()) {
                _loginState.postValue(Resource.error("账号或密码不能为空", null))
                return
            }
            // 订阅Repository返回的LiveData,更新状态
            repository.login(account, pwd).observeForever {
                _loginState.postValue(it)
            }
        }
    
        override fun onCleared() {
            super.onCleared()
            // 移除observeForever的监听,避免内存泄漏
        }
    }
    
    // 配套的ViewModelFactory,解决带参实例化的报错
    class LoginViewModelFactory(
        private val application: Application,
        private val repository: LoginRepository
    ) : ViewModelProvider.Factory {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(LoginViewModel::class.java)) {
                return LoginViewModel(application, repository) as T
            }
            throw IllegalArgumentException("不支持的ViewModel类型")
        }
    }
    
  • 第三步:重构LoginActivity的观察逻辑,解决Activity环节的编译报错
    高频报错根因:

    • 没有通过ViewModelProvider获取绑定生命周期的ViewModel实例,直接new ViewModel导致生命周期失效、类型不匹配
    • 残留之前纯Retrofit版本的网络请求回调,导致代码逻辑重叠、空指针
      正确实现:
    class LoginActivity : AppCompatActivity() {
        private val loginViewModel: LoginViewModel by lazy {
            // 初始化Retrofit与ApiService
            val retrofit = Retrofit.Builder()
                .baseUrl("你的接口基础路径")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
            val apiService = retrofit.create(ApiService::class.java)
            val repository = LoginRepository.getInstance(apiService)
            // 通过Factory获取绑定当前生命周期的ViewModel实例
            ViewModelProvider(this, LoginViewModelFactory(application, repository))[LoginViewModel::class.java]
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_login)
    
            // 绑定LiveData观察,自动感知生命周期,不会内存泄漏
            loginViewModel.loginState.observe(this) { state ->
                when (state.status) {
                    Resource.Status.LOADING -> {
                        // 展示登录加载框
                    }
                    Resource.Status.SUCCESS -> {
                        // 登录成功,存储用户信息后跳转主页
                        val userInfo: Data = state.data?.data ?: return@observe
                        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
                    }
                    Resource.Status.ERROR -> {
                        // 展示错误提示
                        Toast.makeText(this, state.message, Toast.LENGTH_SHORT).show()
                    }
                }
            }
    
            // 登录按钮点击,仅触发ViewModel逻辑,不写网络请求代码
            btn_login.setOnClickListener {
                val inputAccount = et_account.text.toString().trim()
                val inputPwd = et_pwd.text.toString().trim()
                loginViewModel.startLogin(inputAccount, inputPwd)
            }
        }
    }
    

高频编译报错规避提示

  • 不要把Retrofit的Call对象直接作为LiveData的泛型类型,Call对象无法感知组件生命周期,会在组件销毁时无法自动取消请求
  • 不要在ViewModel里直接调用Toast、findViewById等依赖Activity上下文的方法,所有UI操作全部交由Activity在LiveData回调中处理
  • 不要对外暴露ViewModel内部的MutableLiveData实例,只返回不可变的LiveData,避免外部随意修改状态导致逻辑错乱

内容的提问来源于stack exchange,提问作者android dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 02:36:03