Hey guys, this is not really kotlin specific but I...
# android
g
Hey guys, this is not really kotlin specific but I have a weird issue with a shared viewmodel between an activity and fragment: The activity's observer is only executed once, whereas the fragment's observer is executed on every update. Any ideas why this might be?
r
set observe in Fragment at
onCreate
instead of
onViewCreated
. Fragment lifecycle is different from Activity and doesn't die, so every time Fragment is shown again it will handle observable from viewmodel even if no updates
g
I have the observers in
onStart
. Trying to observe the viewmodel in
onCreate
doesn't work as with the error
IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView()
. As far as I can tell the problem is not with the fragment, as it receives the updates correctly. But the activity doesn't
r
ok, I thought that problem was fragment observer many times
g
The fragment receives every update correctly, but the activity only the first
r
but activity receives observable first time at least, no?
g
yes
r
any other changes activity doesn't?
😐
g
This is what the log outputs, people is the livedata:
Copy code
observer called in fragment, people: 1
observer called in activity, people: 1
observer called in fragment, people: 2
observer called in fragment, people: 3
observer called in fragment, people: 4
observer called in fragment, people: 3
r
wow
g
it doesn't depend on the livedata itself either, because all other livedata's also only get 1 update when starting
r
are you using a ViewModelProvider or koin to share viewmodel?
g
ViewModelProviders
r
I'm sorry @Gilles Braun, have no idea why
g
thanks for your time 🙂
r
seems like SingleLiveEvent that don't propagate to more observers
I don't know
g
I just found the problem, they were 2 separate viewmodel instances, not the same. The reason it always sent the first update is because Viewmodel initilizes its value.
It works now when I instantiate it like this:
ViewModelProviders.of(getActivity()).get(..)
r
jaja just this
fine 😄
have you tried koin? is simple to share viewmodel and provide them
g
This app has already Dagger implemented, so I would have to use that
g
if you have 2 separate instances of viewModel that might mean you have 2 fragments where you are supposed to have just one. And that is why switching to activity helps. I would suggest to check
this
pointers every time you hit a breakpoint in the LiveData observer and validate this