https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
u

ubu

11/04/2018, 11:31 AM
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

Sangeet

11/04/2018, 8:08 PM
Are you getting ViewModel by passing
getActivity()
u

ubu

11/06/2018, 12:46 PM
@Sangeet, no, by passing Fragment.
m

muralimohan962

11/07/2018, 8:05 AM
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
3 Views