How to use data from one ViewModel in another ViewModel - android

I have an AddressesViewModel which holds the user's favorite addresses and another SearchViewModel which holds searched addresses. when user searched an address I have to check whether this address is favorite or not by checking in the favorites array. what is the proper way to do it?
I've already tried subscribing to the AddressesViewModel from the SearchViewModel but I'm looking for other options as it's creating too much dependency between those view models.

Another alternative if I understand the question correctly.
Assuming that you first have this:
ViewModelChild(constructor etc) : ViewModelParent(){
// you can create a var/val to observe a variable in viewmodel parent.
// upon observation of
//this you can change other variables assigned here.
}

You will have to attach two ViewModels to the same lifecycle owner. eg You have an activity named MainActivity, two ViewModels named AddressesViewModel and SearchViewModel and you need to get a variable named address for SearchViewModel to AddressesViewModel
class MyActivity: AppCompactAvtivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
.
.
// Attach the ViewModels
val addressViewModel = ViewModelProviders.of(this).get(AddressesViewModel::class.java)
val searchViewModel = ViewModelProviders.of(this).get(SearchViewModel::class.java)
// Listen to address which is in SearchViewModel
searchViewModel.address.observe(this, Observer { address ->
// Send the variable to AddressesViewModel using a public method
val favOrNot addressViewModel.isAddressFavourite(address)
// or
addressViewModel.favouriteAddress = address
})
}
}
Hope this answers your question.

Related

How should I go about implementing MVVM architecture pattern in my project?

I know this is a very documented topic, but I couldn't find a way to implement it in my project, even after spending hours trying to figure it out.
My root problem is that I have a RecyclerView with an Adapter whose content isn't updating as I'd like. I'm a beginner in Android, so I didn't implement any MVVM or such architecture, and my project only contains a repository, fetching data from Firebase Database, and passing it to a list of ShowModel, a copy of said list being used in my Adapter to display my shows (In order to filter/sort them without modifying the list with all shows).
However, when adding a show to the database from another Activity, my Adapter isn't displaying the newly added show (as detailed here)
I was told to use LiveData and ViewModel, but even though I started understanding how it works after spending time researching it, I don't fully get how I should use it in order to implement it in my project.
Currently I have the following classes:
The Adapter:
class ShowAdapter(private val context: MainActivity, private val layoutId: Int, private val textNoResult: TextView?) : RecyclerView.Adapter<ShowAdapter.ViewHolder>(), Filterable {
var displayList = ArrayList(showList)
class ViewHolder(view : View) : RecyclerView.ViewHolder(view){
val showName: TextView = view.findViewById(R.id.show_name)
val showMenuIcon: ImageView = view.findViewById(R.id.menu_icon)
}
#SuppressLint("NewApi")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
return ViewHolder(view)
}
#SuppressLint("NewApi", "WeekBasedYear")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentShow = displayList[position]
val index = holder.adapterPosition
holder.showName.text = currentShow.name
holder.itemView.setOnClickListener{ // Display show content
val intent = Intent(context, DetailsActivity::class.java)
intent.putExtra("position", index)
startActivity(context, intent, null)
}
holder.showMenuIcon.setOnClickListener{
val popupMenu = PopupMenu(context, it)
popupMenu.menuInflater.inflate(R.menu.show_management_menu, popupMenu.menu)
popupMenu.show()
popupMenu.setOnMenuItemClickListener {
when(it.itemId){
R.id.edit -> { // Edit show
val intent = Intent(context, AddShowActivity::class.java)
intent.putExtra("position", index)
startActivity(context, intent, null)
return#setOnMenuItemClickListener true
}
R.id.delete -> { // Delete show
val repo = ShowRepository()
repo.deleteShow(currentShow)
displayList.remove(currentShow)
notifyItemRemoved(index)
return#setOnMenuItemClickListener true
}
else -> false
}
}
}
}
override fun getItemCount(): Int = displayList.size
// Sorting/Filtering methods
}
The fragment displaying the adapter:
class HomeFragment : Fragment() {
private lateinit var context: MainActivity
private lateinit var verticalRecyclerView: RecyclerView
private lateinit var buttonAddShow: Button
private lateinit var showsAdapter: ShowAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_home, container, false)
context = getContext() as MainActivity
buttonAddShow = view.findViewById(R.id.home_button_add_show)
buttonAddShow.setOnClickListener{ // Starts activity to add a show
startActivity(Intent(context, AddShowActivity::class.java))
}
verticalRecyclerView = view.findViewById(R.id.home_recycler_view)
showsAdapter = ShowAdapter(context, R.layout.item_show, null)
verticalRecyclerView.adapter = showsAdapter
return view
}
}
The MainActivity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadFragment(HomeFragment())
}
private fun loadFragment(fragment: Fragment){
val repo = ShowRepository()
if(showsListener != null) databaseRef.removeEventListener(showsListener!!)
repo.updateData{
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, fragment)
transaction.addToBackStack(null)
if(supportFragmentManager.isStateSaved)transaction.commitAllowingStateLoss()
else transaction.commit()
}
}
}
The repository:
class ShowRepository {
object Singleton{
val databaseRef = FirebaseDatabase.getInstance().getReference("shows")
val showList = arrayListOf<ShowModel>()
var showsListener: ValueEventListener? = null
}
fun updateData(callback: () -> Unit){
showsListener = databaseRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
showList.clear()
for(ds in snapshot.children){
val show = ds.getValue(ShowModel::class.java)
if(show != null) showList.add(show)
}
callback()
}
override fun onCancelled(p0: DatabaseError) { }
})
}
fun insertShow(show: ShowModel){
databaseRef.child(show.id).setValue(show)
}
fun deleteShow(show: ShowModel){
databaseRef.child(show.id).removeValue()
}
}
From what I understand of LiveData and ViewModel, what I should do is creating a ShowViewModel containing a MutableLiveData<List<ShowModel>> containing the shows, and then observe it in my HomeFragment and update the adapter depending on the changes happening. However, everytime I start something to implement it, I encounter a situation where I'm lost and don't know what I should do, which leads me back to square one once again. I've been trying this for more than a week without progressing even a little bit, and that's why I'm here, hoping for some insight.
Sorry for the silly question and the absurd amount of informations, and hoping someone will be able to help me understand what I do wrong/should do.
(this ended up longer than I meant it to be - hope it's not too much! There's a lot to learn, but you don't have to make it super complicated at first)
Broadly, working backwards, it should go like this:
Adapter
displays whatever the Fragment tells it to (some kind of setData function that updates its internal list and refreshes)
passes events to the Fragment (deleteItem(item), showDetails(item) etc.) - don't have the Adapter doing things like starting Activites, that's not its responsibility
Fragment
grabs a reference to any ViewModels (only certain components like Fragments and Activities can actually "own" them)
observes any LiveData (or collects Flows if you're doing it that way) on the VM, and updates stuff in the UI in response
e.g. model.shows.observe(viewLifecycleOwner) { shows -> adapter.setData(shows) }
handles UI events and calls methods on the VM in response, e.g. click listeners, events from the Adapter
ViewModel
acts as a go-between for the UI (the Fragment) and the data layer (the repository)
exposes methods for handling events like deleting items, interacts with the data layer as required (e.g. calling the appropriate delete function)
exposes data state for the UI to observe, so it can react to changes/updates (e.g. a LiveData containing the current list of shows that the data layer has provided)
That's the basic setup - the VM exposes data which the UI layer observes and reacts to, by displaying it. The UI layer also produces events (usually down to user interaction) which are passed to the VM. You can read more about this general approach in this guide about app architecture - it's worth reading because not only is it recommended as a way to build apps, a lot of the components you use in modern Android are designed with this kind of approach in mind (like the reactive model of wiring stuff up).
You could handle the Adapter events like this:
// in your Adapter
var itemDeletedListener: ((Item) -> Unit)? = null
// when the delete event happens for an item
itemDeletedListener?.invoke(item)
// in your Fragment
adapter.itemDeletedListener = { viewModel.deleteItem(it) }
which is easier than implementing an interface, and lets you wire up your Adapter similar to doing setOnClickListener on a button. Notice we're passing the actual Item object here instead of a list index - generally this is easier to work with, you don't need to maintain multiple copies of a list just so you can look up an index given to you by something else. Passing a unique ID can make sense though, especially if you're working with a database! But usually the object itself is more useful and consistent
The data layer is the tricky bit - the ViewModel needs to communicate with that to get the current state. Say you delete an item - you then need to get the current, updated list of shows. You have three approaches:
Call the delete function, immediately after fetch the current data, and set it on the appropriate LiveData
This can work, but it's not very reactive - you're doing one action, then immediately doing another because you know your data is stale. It would be better if the new data just arrived automatically and you could react to that by pushing it out. The other issue is that calling the delete function might not have an immediate effect - if you fetch the current data, nothing might have changed yet. It's better if the data layer is responsible for announcing updates.
This is the simplest approach though, and probably a good start! You could run this task in a coroutine (viewModelScope.launch { // delete and fetch and update LiveData }) so any slowness doesn't block the current thread.
Have the data layer's functions return the current, updated data that results
Similar to above, you're just sort of pushing the fetching into the data layer. This requires all those functions to be written to return the current state, which could take a while! And depending on what data you want, this might be impossible - if you have an active query on some data, how does the function know what specific data to return?
Make the ViewModel observe the data it wants, so when the data layer updates, you get the results automatically
This is the recommended reactive approach - again it's that two-way idea. The VM calling a function on the data layer is completely separate from the VM receiving new data. One thing just happens as a natural consequence of the other, they don't need to be tied together. You just need to wire them up right!
How do you actually do that though? If you're working with something like Room, that's already baked in. Queries can return async data providers like LiveData or Flows - your VM just needs to observe those and expose the results, or just expose them directly. That way, when a table is updated, any queries (like the current shows) push a new value, and the observers receive it and do whatever they need to do, like telling the Adapter to display the data. It all Just Works once it's wired up.
Since you have your own repo, you need to expose your own data sources. You could have a currentShows LiveData or (probably preferably) the flow equivalent, StateFlow. When the repo initialises, and when any data is changed, it updates that currentShows data. Anything observing that (e.g. the VM, the Fragment through a LiveData/Flow that the VM exposes) will automatically get the new values. So broadly:
// Repo
// this setup is exactly the same as your typical LiveData, except you need an initial value
private val _currentShows = MutableStateFlow<List<Show>>(emptyList()) // or whatever default
val currentShows: StateFlow<List<Show>> = _currentShows
fun deleteItem(item: Item) {
// do the deletion
// get the updated show list
_currentShows.value = updatedShowList
}
// ViewModel
// one way of doing things - you have a lot of options! This literally just exposes
// the state from the data layer, and turns it into a LiveData (if you want that)
val currentShows = repo.currentShows.asLiveData()
// Fragment
// wire things up so you handle new data as it arrives
viewModel.currentShows.observe(viewLifecycleOwner) { shows -> adapter.setData(shows) }
That's basically it. I've skimmed over a lot because honestly, there's a lot to learn with this - especially about Flows and coroutines if you're not already familiar with those. But hopefully that gives you an overview of the general idea, and don't be afraid to take shortcuts (like just updating your data in the ViewModel by setting its LiveData values) while you're learning and getting the hang of it. Definitely give that app architecture guide a read, and also the guides for ViewModels and LiveData. It'll start to click when you get the general idea!

Coroutines and ViewModel best practice for separation of concers

I needed some direction on being able to observe some flow as live data in my ViewModel class.
For example: The ViewModel class has the field userDataFlow below which combines a few streams of Data Flow. I want to be able to extract out the work of that field into a separate class and let all of the inner working take place there and just want to observe the LiveData to the field in the ViewModel. I would need to pass in few things in the Parameter of that class from the ViewModel which the Flow would need in order to work. Not sure if this is a good practice. Basically, let my ViewModel observe the result and pass it along to the View.
val userDataFlow: Flow<List<UserData>> =
combine(
familyChannel.asFlow(),
userRealTimeData.asFlow,
).asLiveData()
}
Sounds like you need a UseCase/Interactor which in short processes data coming from different repositories.
For example suppose you want a list of your friends that live in countries with a COVID-19 infection rate above a certain value:
class GetFriendsInDangerUseCase(
private val friendsRepository: FriendsRepository,
private val countryRepository: CountryRepository)
fun invoke(threshold: Float) = friendsRepository.friendsFlow
.combine(countryRepository.countriesFlow) { friends, countries ->
val dangerousCountries = countries.filter { it.infectionRate >= threshold }
friends.filter { it.country in dangerousCountries }
}
Then use it like this from your VM:
val friendsInDangerFlow = getFriendsInDanger(0.5)

How to Initialize an Object and access its values from different methods - Kotlin

I am kind of new to Android. I can't figure this out. I want to create an object that is accessible from two different functions. Here is the object:
class Person(var firstName: String="", var lastName: String="", var order: List<Orders> )
class Order(var orderId: String="", var orderTitle: String="")
Then in an activity:
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var order: Order()
var person: Person(order) //I am sure I am not doing this right
}
fun Function1(){
person.order[1].orderTitle = "New Order" //to update order title
}
fun Function2(){
// to read new order title
var newOrderTitle = person.order[1].orderTitle
}
}
You created your Person instance as a local variable inside the onCreate() function, so it is only accessible inside the onCreate() function. To make it accessible from your other functions, it needs to be a property member of the class (defined outside any functions). You also need to use the = symbol to set the initial value. The : symbol is for declaring what type the property or variable is, and is optional in most cases.
By the way, in Kotlin, the convention is to always start function names with a lower-case letter, so it is easy to distinguish them from constructors. (This differs from languages like C#, where the new keyword makes constructor calls obvious.)
class MainActivity : AppCompatActivity(){
var order = Order()
var person = Person(order)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun function1(){
person.order[1].orderTitle = "New Order" //to update order title
}
fun function2(){
// to read new order title
var newOrderTitle = person.order[1].orderTitle
}
}
As well as what #TenFour04 says about making the variables visible to the functions, there's a couple of problems with how you're creating your Person object.
First, you're using default values for everything so you don't need to pass in a value for every parameter, right? That's how you can call Order() without providing any other data. But if you are passing in data, like with your Person(order) call, you need to tell it which parameter you're passing by using a named argument:
Person(order = order)
using the same name for the variable you're passing in and the name of the argument maybe makes it look more confusing, but you're specifically saying "the argument called order, here's a value for it".
You can pass in arguments without names, but you have to provide them in the order they're declared - so the 1st argument (a String), or the 1st and 2nd, or the 1st, 2nd and 3rd. Since you want to jump straight to the 3rd argument, you need to explicitly name it.
Second issue is your 3rd argument's type isn't Order, it's a List of orders. You can't just pass in one - so you need to wrap it in a list:
Person(order = listOf(order))
that's all you need to do!
The third problem is you've actually written the type as List<Orders> (sorry about the formatting). The type is Order, so we say List<Order> because it's a list holding objects of the Order type. You can use plurals in your variable names though (like val listOfOrders: List<Order>)

Should livedata be always used in ViewModel?

It seems like recommended pattern for fields in viewmodel is:
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
(btw, is it correct that the selected field isn't private?)
But what if I don't need to subscribe to the changes in the ViewModel's field. I just need passively pull that value in another fragment.
My project details:
one activity and a bunch of simple fragments replacing each other with the navigation component
ViewModel does the business logic and carries some values from one fragment to another
there is one ViewModel for the activity and the fragments, don't see the point to have more than one ViewModel, as it's the same business flow
I'd prefer to store a value in one fragment and access it in the next one which replaces the current one instead of pass it into a bundle and retrieve again and again manually in each fragment
ViewModel:
private var amount = 0
fun setAmount(value: Int) { amount = value}
fun getAmount() = amount
Fragment1:
bnd.button10.setOnClickListener { viewModel.setAmount(10) }
Fragment2:
if(viewModel.getAmount() < 20) { bnd.textView.text = "less than 20" }
Is this would be a valid approach? Or there is a better one? Or should I just use LiveData or Flow?
Maybe I should use SavedStateHandle? Is it injectable in ViewModel?
To answer your question,
No, It is not mandatory to use LiveData always inside ViewModel, it is just an observable pattern to inform the caller about updates in data.
If you have something which won't be changed frequently and can be accessed by its instance. You can completely ignore wrapping it inside LiveData.
And anyways ViewModel instance will be preserved and so are values inside it.
And regarding private field, MutableLiveData should never be exposed outside the class, as the data flow is always from VM -> View which is beauty of MVVM pattern
private val selected = MutableLiveData<Item>()
val selectedLiveData : LiveData<Item>
get() = selected
fun select(item: Item) {
selected.value = item
}

Pass data from different class

I'm tring to pass the data of label to the LivePreviewActivity. Is there a better way to do this ? I don't know if the UIThread is working. I have also need the UIThread because i need to log the data continuously. For now the Log doesn't print on the console. My goal is accessing the label text on the Activity. Thanks. Please correct me if I'm doing this wrong. This is a quick-start project MLKit on Firebase. Any help will be wonderful. I have also need the UIThread because i need to log the data continiously.
class LivePreviewActivity : AppCompatActivity(), OnRequestPermissionsResultCallback,
OnItemSelectedListener, CompoundButton.OnCheckedChangeListener {
var labelName: String? = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_live_preview)
runOnUiThread {
Log.d("LivePreviewActivity", labelName)
}
}
ImageLabelProcessor
class ImageLabelingProcessor : VisionProcessorBase<List<FirebaseVisionImageLabel>>() {
val livePreviewActivity = LivePreviewActivity()
for (label in labels) {
livePreviewActivity.labelName = label.text
}
}
}
The typical way of passing values to Activities is via the intent you used to create the Activity. You shouldn't be creating Activities directly, as they have lifecycles.
val intent = Intent(context, LivePreviewActivity::class.java)
intent.putExtra(labelKey, labelValue)
where context is your current Activity, labelKey just a little const your will use for a lookup, labelValue your value you want to set.
and then in your activity's onCreate, you look up the extra using the bundle.
Hope this helps and that I understood your question correctly!

Categories

Resources