'NavArgs, Large data and ViewModel

Problem

In my application I have to use an object that we'll call Product through different Fragments. Actually I pass Product through arguments, and I store it in my ViewModel :

class MyFragment : Fragment() {

    private val viewModel: MyViewModel by viewModels()
}

class MyViewModel @Inject constructor(private val savedStateHandle: SavedStateHandle) : ViewModel() {

    val product: Product = savedStateHandle["product"]!!
}

@Parcelize
data class Product(val id: Int, ...) : Parcelable

The problem is that my object Product can be a large object, so it may happen that I get TooLargeException we my app enter in background or when I navigate between fragments.

Questions

So, how can I avoid this exception ?

My Product is too large, so I thought to save it in DDB with Room and then save Product.id in SavedStateHandle and retrieve the object with that id if necessary. I thought to use a Repository but I'm not aware with that method.

How can I get Product through navArgs at first, and then use its id if necessary to retrieve the object from DDB ? Or maybe there is another solution ?

Thank you for help, have a nice week !



Solution 1:[1]

You have multiple solutions for this problem,

  1. put Product in a companion object, so you can access it from the next activity or fragment:
class YourFirstActivity : BaseActivity() {
    companion object {
        val product: Product = Product(...)
    }
}

You can access the product from anywhere.

  1. As you said, you can save the product in your room database and access that using the id property.

In general, if the product contains a lot of information and you need most of that data in another activity or fragment. These two methods will be a good suggestion for you. But if you do not need most of the data from product, you can save the required information in a new model and give it as an argument to the next fragment or activity.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Milad Mohammadi