Reputation: 1256
My LiveData
is not working.
ViewModel
:
private var _email = MutableLiveData<String>()
fun setEmail(){
_email.postValue("[email protected]")
}
fun getEmail(): LiveData<String>{
return _email
}
Fragment
's onViewCreated
method
:
mViewModel.getEmail().observe(viewLifecycleOwner, Observer {
tvEmail.text = it
})
mViewModel.setEmail() //Trying to post data to my LiveData.
The above code is not working as tvEmail
is not chaning.
However, if I trust a button for posting data to LiveData like this, it is working:
//Inside fragment again
button.setOnClickListener {
mViewModel.setEmail()
}
When user clicks button, text in tvEmail
is changing. If user does not click, nothing is happening. What am I missing here?
Edit:
I have just tested the code with Activity
. Surprisingly, for Activity
s it is working but not for Fragment
s.
Upvotes: 0
Views: 54
Reputation: 1287
@Azizjon Kholmatov - Best practice you can write your code inside the "onActivityCreated" function
please refer this. If you still having the problem let me know in comments section. I am happy to help. :)
class MainFragment : Fragment() {
companion object {
fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
viewModel.getEmail().observe(viewLifecycleOwner, Observer {
tvEmail.text = it
})
viewModel.setEmail("[email protected]")
button.setOnClickListener {
viewModel.setEmail("[email protected]")
}
}
}
And ViewModel class as follows
class MainViewModel : ViewModel() {
private var _email = MutableLiveData<String>()
fun setEmail(email: String = "[email protected]") {
_email.postValue(email)
}
fun getEmail(): LiveData<String> {
return _email
}
}
Upvotes: 1