https://kotlinlang.org logo
#android
Title
# android
d

Diego Almeida de Oliveira

12/17/2019, 3:16 PM
Hey guys 👋. From what I know a ViewModel shouldn't know anything about Android, meaning that it should not receive references such as Intent, Bundle, Uri, etc. Having this in mind, let's say I receive a lot of information from an Intent and I have a complex logic related to all this data. I believe the right way to do it is by delegating this logic to the ViewModel, but since ViewModel shouldn't receive the Intent, what would be a good approach? I came up with these approaches: 1. Get all data in the View layer and pass to the ViewModel through a function. This might not be good because as far as I know passing too many parameters to a function is not good. 2. Create a data class that will have all the data. In this way we might end up having too many data classes. 3. Create an interface that hides any Android related code:
Copy code
interface IntentInterface {
    fun getStringExtra(name: String?): String
    fun getIntExtra(name: String?): Int
    ...
}

class CustomIntent : Intent, IntentInterface {

    constructor() : super()
    constructor(intent: Intent?) : super(intent)
    constructor(packageContext: Context?, cls: Class<*>?) : super(packageContext, cls)
    ...
}

class SampleActivity: AppCompatActivity() {
	...
	fun handleIntent() {
		viewModel.processReceivedData(CustomIntent(intent))
	}
	...
}

class SampleViewModel: ViewModel() {
	...
	fun processReceivedData(data: IntentInterface) {
		val sampleValue = data.getStringExtra("sample_key")
		...
	}
	...
}
w

wasyl

12/17/2019, 8:56 PM
Do you have an example of data you would like to pass? Because I feel data passed through the Intent should be pretty limited — e.g. an item ID and not an entire object, or an enum representing desired reusable activity functionality vs bunch of specific parameters
1
With this passing them through a function/constructor shouldn’t really be a problem
i

Isaac Udy

12/18/2019, 5:31 AM
The other option is to pass all of the arguments as a single Parcelable object, and then pass that object to the ViewModel.
d

Dmitry Khasanov

12/18/2019, 10:48 AM
What advantages you get trying to avoid using Intent or Bundle inside ViewModel?
4 Views