airbnb / mavericks

Mavericks: Android on Autopilot
https://airbnb.io/mavericks/
Apache License 2.0
5.85k stars 499 forks source link

Use ActivityViewModelContext for activity scope #676

Closed apramana closed 1 year ago

apramana commented 1 year ago

Fixes: #674

parentFragment should not get set if the scope is an activity.

vulpeszerda commented 1 year ago

@apramana I think just removing findFragmentFromView discards some functionality.

How about this?

val parentFragment = scope as? Fragment ?: if (scope !is Activity) findFragmentFromView(view) else null

if (parentFragment != null) {
    val args = argsFactory?.invoke() ?: parentFragment.arguments?.get(Mavericks.KEY_ARG)
    FragmentViewModelContext(activity, args, parentFragment)
} else {
    val args = argsFactory?.invoke() ?: activity.intent.extras?.get(Mavericks.KEY_ARG)
    ActivityViewModelContext(activity, args, viewModelStoreOwner, savedStateRegistry)
}
apramana commented 1 year ago

@apramana I think just removing findFragmentFromView discards some functionality.

How about this?

val parentFragment = scope as? Fragment ?: if (scope !is Activity) findFragmentFromView(view) else null

if (parentFragment != null) {
    val args = argsFactory?.invoke() ?: parentFragment.arguments?.get(Mavericks.KEY_ARG)
    FragmentViewModelContext(activity, args, parentFragment)
} else {
    val args = argsFactory?.invoke() ?: activity.intent.extras?.get(Mavericks.KEY_ARG)
    ActivityViewModelContext(activity, args, viewModelStoreOwner, savedStateRegistry)
}

Yeah I suppose scope could be a non-fragment/activity lifecycle owner... updated to use a when expression.

elihart commented 1 year ago

Thanks!

rossbacher commented 1 year ago

@apramana This is now part of release v3.0.6 that I just made.

apramana commented 1 year ago

@apramana This is now part of release v3.0.6 that I just made.

Thanks @rossbacher !