Android LiveData:无法接收有关Observable的更新?

时间:2018-10-01 14:01:09

标签: android-livedata mutablelivedata

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

  

AuthRepository

    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
    }
}
  

LoginViewModel

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

    var _showOtpScreen: MutableLiveData<Boolean> = MutableLiveData()

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

LoginFragment

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,它只能以空值被调用一次,并且在服务调用完成后再也不会被调用。

1 个答案:

答案 0 :(得分:0)

Event wrapper是上述问题的解决方案。