Reputation: 307
Hi guys its my first shot to livedata and i will be thankful if you help me to find whats wrong with this Observer
Observer section in my MainActivity can't receive anything, every thing is ok from my Dialogfragment and MainModel class to MainViewModel and I've got triggered logs but nothing happens to Observer in MainActivity
class MainModel {
private var resultLiveData = MutableLiveData<List<Course>>()
private val courseList = ArrayList<Course>()
private val mainViewModel = MainViewModel()
fun sum(course: Course) {
courseList.add(course)
resultLiveData.value = courseList
Log.d("tag", "$course in model")
mainViewModel.loadedResult(resultLiveData)
Log.d("tag", "${resultLiveData.value} in my model")
}
}
class MainViewModel : ViewModel() {
var result = MutableLiveData<List<Course>>()
fun loadedResult(resultData: MutableLiveData<List<Course>>) {
result = resultData
Log.d("tag", "main viewModel ${result.value}")
Log.d("tag", "main viewModel ${resultData.value}")
}
}
class MainActivity : AppCompatActivity() {
private lateinit var fragmentManager: FragmentManager
private lateinit var linearLayoutManager: LinearLayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
linearLayoutManager = LinearLayoutManager(this)
mainRecyclerView.layoutManager = linearLayoutManager
fragmentManager = supportFragmentManager
setupLivedata()
floatingActionButton.setOnClickListener {
showAddDialog()
}
}
private fun setupLivedata() {
val mainViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
var myList : ArrayList<Course>
var myObserver = Observer<List<Course>> {
observedList -> myList = observedList as ArrayList<Course>
Log.d("tag", "${myList.size} reached main activity")
Log.d("tag", "${observedList.size} reached main activity")
}
mainViewModel.result.observe(this, myObserver)
}
private fun showAddDialog() {
val inputDialog = InputDialogFragment()
inputDialog.show(supportFragmentManager, "input")
}
}
Upvotes: 0
Views: 825
Reputation: 1265
You are changing LiveData reference in MainViewModel
on this line:
result = resultData
with LiveData you need to setValue/postvalue
new items to actually trigger observers.
Something like this:
class MainViewModel : ViewModel() {
val result = MediatorLiveData<List<Course>>()
fun loadedResult(resultData: MutableLiveData<List<Course>>) {
result.addSource(resultData, { resultObj ->
result.setValue(resultObj);
});
Log.d("tag", "main viewModel ${result.value}")
Log.d("tag", "main viewModel ${resultData.value}")
}
}
Suggestion: better to keep LiveData immutable and not change it once created. And just update the value.
Upvotes: 1
Reputation: 2727
MainModel.mainViewModel
and MainActivity.mainViewModel
are different instances.
You shouldn't use ViewModel like this
private val mainViewModel = MainViewModel()
Upvotes: 2