Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting arguments with getKey working first time but not the second #260

Closed
MikaReesu opened this issue Jul 5, 2022 · 10 comments
Closed

Comments

@MikaReesu
Copy link

MikaReesu commented Jul 5, 2022

Hello,

In a Splashcreen, I first use this to go to the HomeFragment, so the key is already created :

backstack.setHistory(History.of(HomeScreen(0, true), StateChange.FORWARD)

In a child view(a fragment) I use goTo with different data than the Splashscreen to pass to the HomeFragment.
After this goTo I get the data of the Splashscreen in the HomeFragment, I guess cause the key is already created.

backstack.goTo(HomeScreen(2, true))

When I go back to the childview and when I use goTo again, this, time the data is passed to the HomeScreen. So the second time I use the goTo in the child is the moment when I finally send the good data to HomeFragment.

HomeFragment(to get the data) :
val (indexPage, isRedirected) = getKey<HomeScreen>() if(isRedirected == true){ selectedIndex = indexPage }

HomeScreen :

`
@parcelize
data class HomeScreen(
val indexPage: Int,
val isRedirected: Boolean? = false
): ScreenKey() {
override fun instantiateFragment(): Fragment {
return HomeFragment()
}

override fun bindServices(serviceBinder: ServiceBinder) {
    with(serviceBinder){
        add(HomeViewModel(lookup(), backstack, lookup()))
    }
}

}
`

I hope I was clear enough, and you need more code than this, I will add it.

Thank you for your help.

@Zhuinden
Copy link
Owner

Zhuinden commented Jul 5, 2022

Heyo,

Keys are passed to Fragments as arguments (via setArguments(Bundle().apply { putParcelable(DefaultFragmentArgs.ARGS_KEY, key))), and fragment arguments don't change over time once they are already set.

Also, by default, the getFragmentTag() returns getClass().getName(); as the "unique identifier" of a fragment, but if you are okay with destroying the previously existing HomeFragment and its scope, and replace it with a new scope, you can do return toString();, in which case the Fragment will be completely replaced with a new instance with the new arguments set.

Otherwise, normally I keep such selection state in a BehaviorRelay/MutableLiveData/MutableStateFlow etc and only use the key as the initial parameter for it. That way I can make changes to the selected state, keep it across process death, but don't try to override the initial arguments.

I hope that helps think of a solution, currently what happens in your case is "expected" (because of how fragment arguments are intended to work + what the default value of the fragment tag is) .

@MikaReesu
Copy link
Author

MikaReesu commented Jul 6, 2022 via email

@Zhuinden
Copy link
Owner

Zhuinden commented Jul 6, 2022

...that moment when you've been using this for ages but you don't have an open-source example 🤔

Anyhoo, the idea is that HomeViewModel can be passed the key as a constructor parameter, and in HomeViewModel you could do

private val selectedIndex = MutableLiveData(key.selectedIndex)

Once you have this, then you can persist the selected index via Bundleable

class HomeViewModel(...): Bundleable {
    ...

    override fun toBundle(): StateBundle = StateBundle().apply {
        putInt("selectedIndex", selectedIndex.value)
    }

    override fun fromBundle(bundle: StateBundle?) {
        bundle?.run {
            selectedIndex = getInt("selectedIndex", 0)
        }
    }
}

Once you have that, you can update the value in HomeViewModel easily

private val homeViewModel by lazy { lookup<HomeViewModel>() }

...

homeViewModel.updateSelectedIndex(newIndex)

And then you don't have to use the key to do it and you keep the ViewModel/Fragment instead of destroying them.


Not sure if overhead, I'm kinda used to it as this is how Fragment arguments worked in general as far as I'm aware 🤔 or at least in case of Activities, you were definitely not able to re-define the extras and actually preserve this change, which is why DefaultFragmentStateChanger doesn't try to invoke fragment.setArguments( on each state change, but only on creation.

Please notify if this solves your issue

@MikaReesu
Copy link
Author

That's interesting, I think it will be much cleaner to use this method.

I still have a few questions related to that.

private val selectedIndex = MutableLiveData(key.selectedIndex)
Where is the "key.selectedIndex" coming from?

So, the value is passing by the bundle of the ViewModel and not by the HomeScreen if I understand well.

And, finally the last piece of code will be used in the child Fragment to update the data before doing the goTo right?

private val homeViewModel by lazy { lookup<HomeViewModel>() }
homeViewModel.updateSelectedIndex(newIndex)

Thank you for your help and the time you take to answer.

@Zhuinden
Copy link
Owner

Zhuinden commented Jul 6, 2022

Where is the "key.selectedIndex" coming from?

That code is assuming that you keep it as initial param, but serviceBinder which creates the homeViewModel in add(HomeViewModel(lookup(), backstack, lookup())) actually has a getKey<T> function (and ``this@HomeScreen` is also the key to begin with) so the VM can be passed arguments during initialization.

So, the value is passing by the bundle of the ViewModel and not by the HomeScreen if I understand well.

That's how I generally do it, because I use args for initialization, but the rest happens via the "ViewModels" (scoped services).

And, finally the last piece of code will be used in the child Fragment to update the data before doing the goTo right?

Yes 👍

@MikaReesu
Copy link
Author

So I need to add the getKey to HomeScreen :

add(HomeViewModel(**getKey()**, lookup(), backstack, lookup()))

In the HomeViewModel, Do I need to declare a key or no? The following code has errors, but is it suppose to be similar to this?

class HomeViewModel(
    private val key: <T>,
private val backstack: Backstack,
) : ScopedServices.Registered, Bundleable {
    private val selectedIndex = MutableLiveData(key.indexPage)

Sorry, to ask again, but I didn't think that I understood all correctly.
Thank you, again!

@Zhuinden
Copy link
Owner

Zhuinden commented Jul 6, 2022

private val key: HomeScreen should work

@MikaReesu
Copy link
Author

Oh I see, yeah working with the HomeScreen.

In the HomeViewModel I created the function updateindexPage.
Is it gonna update it or I need to call toBundle in it?
:

fun updateindexPage(index: Int){
        indexPage.value = index
    }

In the child fragment, is it correct?

homeViewModel.updateindexPage(2)
backstack.goTo(HomeScreen( 2, true))

So, after in the HomeFragment, to get the Value, I can"t do anymore, no?
val (indexPage, isRedirected) = getKey<HomeScreen>()

Do I need to pass by HomeViewModel to get the data here ?

@Zhuinden
Copy link
Owner

Zhuinden commented Jul 6, 2022

In the HomeViewModel I created the function updateindexPage.

Is it gonna update it

It should, because of how LiveData works

or I need to call toBundle in it?

toBundle() is called by simple-stack, it's basically just like onSaveInstanceState.

So, after in the HomeFragment, to get the Value, I can"t do anymore, no?

Well, you should get the selected index from your ViewModel liveData with .observe now.

@MikaReesu
Copy link
Author

Thanks a lot for your help!

It is working perfectly !

@Zhuinden Zhuinden added the done label Jul 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants