Hi there. Consider the following scenario: I have...
# android-architecture
u
Hi there. Consider the following scenario: I have a
Fragment
(A) that subscribes a
ViewModel
(V) in
OnActivityCreated()
. When opening this
Fragment
(A), I receive an update from
LiveData
. Then I open another
Fragment
(B), then get back to the first one (A). It gets inflated, and
onCreateView()
,
onViewCreated()
and
OnActivityCreated()
are called. We've just subscribed the
ViewModel
(V), but it does not emit any item (the most recent update). I'd expect a
LiveData
would behave like a
BehaviorSubject
in
RxJava2
(tell me if this comparison is appropriate), but there are no updates. What could go wrong? Any help would be appreciated.
s
Are you getting ViewModel by passing
getActivity()
u
@Sangeet, no, by passing Fragment.
m
Nope! You have to pass getActivity() to of() method otherwise you won't get the viewmodel of the activity. If you pass fragment to of() method then the viewmodel you get is not the activity's but rather one that is scoped to your specific fragment.
👍 1