Anyone working with mvrx here? i'm using it with A...
# android
s
Anyone working with mvrx here? i'm using it with Android Navigation Component to display a view with bottomNavigation and two fragment. i would like to share an id to those two fragments, but i can't access the activity that contain them... bit lost here with that framework 😥
s
Try android-united
o
I use it. What is your use case?
s
@okarm Right now i'm using Android Navigation component with two activity. The First one display a list of user and the second display with a bottomNavigationView two fragment giving details about that user. So when i select an user in the first activity, i give the id to my second activity and then i want to use that id to fetch the information online... problem, i don't know how to share that id from my 2nd activity to my fragments. My second activity only contain a HostNavigationFragment. When i try to do a getActivity, i only retrieve a FragmentActivity which is not my Activity at all... 🤔 But i'm probably out of the scope of the framework trying to use it like that
o
@Soundlicious This has nothing to do with the Navigation component or MvRx. It's just plain old getting an ID from containing activity. You must cast the result of
getActivity()
to your concrete Activity type.
Copy code
// somewhere inside inside onCreateView, assuming the fragment's containing activity is an instance of ProfileDetailActivity

val userId = (activity as ProfileDetailActivity?)?.userId ?: -1
myViewModel.getUserDetail(userId)
//viewModel handles the case when userId == -1 and sets the state accordingly, otherwise fetches profile detail


// OR IF this fragment could be used inside multiple known Activities, use something like this:
val userId = activity?.let { activity ->
    when(activity) {
        is Activity1 -> activity.getIdFromActivity1() // will be smart cast to type Activity1 for you
        is Activity2 -> activity.getIdFromActivity2() //will be smart cast to type Activity2 for you
        else -> throw IllegalStateException("Containing activity is not of valid type! Actual type: ${activity::class.simpleName}")
    }
} ?: -1