0

我正在使用 android Architecture Component LiveData 使用 Observable LiveData 通知 UI,但它没有被触发。下面是代码片段。

授权库

    class AuthRepository(private val repository:Avails) {


    fun auth(mobile: String): LiveData<Boolean>{
        var data: MutableLiveData<Boolean> = MutableLiveData()
        repository.auth(prepareHeaders(), AuthRequest(mobile))
                .enqueue(object : Callback<AuthResponse>{

                    override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
                        if(response.isSuccessful){

                            data.value = true
                        }
                    }

                    override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
                            data.value = false
                    }
                })

        return data
    }
}

登录视图模型

class LoginViewModel(private val repository: AuthRepository) : ViewModel() {

    var _showOtpScreen: MutableLiveData<Boolean> = MutableLiveData()

    fun auth(mobile: String){
        _showOtpScreen.value =  repository.auth(mobile).value
    }
}

登录片段

class LoginFragment : Fragment() {

    private lateinit var loginViewModel: LoginViewModel

    companion object {
        private const val sTag: String = "LoginFragment"
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val authRepository = AuthRepository(AvailsClient.retrofit.create(Avails::class.java))
        loginViewModel = ViewModelProviders.of(this,LoginViewModelFactory(authRepository)).get(LoginViewModel::class.java)

        loginViewModel._showOtpScreen.observe(this, Observer {

            if(it != null){
                if(it){
                    Log.e(sTag,"OTP RECEIVED")
                    findNavController().navigate(R.id.action_loginFragment_to_verifyOtpFragment)
                }else{
                    Log.e(sTag,"Failed to get OTP")
                }
            }

        })
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_login, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        btnContinue.setOnClickListener {
            loginViewModel.auth(edtPhoneNumber.text.toString())

        }
    }

}

上面的代码无法观察 _showOtpScreen 它只被调用一次,值为空,并且在服务调用完成后不再被调用。

4

1 回答 1

0

事件包装器是上述问题的解决方案。

于 2018-10-05T05:08:17.340 回答