how to pass data from viewModel observer to Global variable in fragment

Viewed 644

This is my code.

public class GetUrlsFragment extends Fragment {

List<Post> mPosts;

private GetUrlsViewModel getUrlsViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        getUrlsViewModel =
                new ViewModelProvider(requireActivity()).get(GetUrlsViewModel.class);


        return inflater.inflate(R.layout.fragment_geturls, container, false);
    }
 @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

getUrlsViewModel.getPosts().observe(getViewLifecycleOwner(), new Observer<List<Post>>() {
            @Override
            public void onChanged(List<Post> posts) {
                mPosts = posts; 
                Log.e( "Inside observer: ", mPosts.toString());
            }
        });
                Log.e( "Outside observer: ", mPosts.toString());

     }

}

in my logCat im getting data for Inside observer. but not getting any value to Outside observer(getting null value).

How can I pass data (Initilize variable) from observer method to Global Variable.

Any one can please say what's I'm doing wrong here?

1 Answers

You should be able to get the current value of the live data by getUrlsViewModel.getPosts().getValue(). But getValue() will only return value once any value is posted to the live data and it is currently being observed.

You can use something like the following to pass an initial value to live data so after it's observed, getValue() will return the initial value immediately.

class InitialValueLiveData<T> private constructor(value: T) : MutableLiveData<T>() {
    companion object {
        fun <T> create(value:T): MutableLiveData<T> {
            return InitialValueLiveData(value)
        }
    }

    init {
        postValue(value)
    }
}

Java version of the code:

public class InitialValueLiveData<T> extends MutableLiveData<T> {
    public InitialValueLiveData(T value) {
        super(value);
        postValue(value);
    }
    
    public static <T> InitialValueLiveData<T> create(T value) {
        return new InitialValueLiveData(value);
    }
}
Related