web-dev-qa-db-fra.com

Quand utiliser Mutablelivedata et Livedata

quand utiliser MutableLiveData et LiveData désigne la zone d'utilisation des méthodes:

MutableLiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData;
}

et quand utiliser ceci,

LiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData
}
28
vinayak

Meilleure approche d'utiliser mutablelivedata dans une classe séparée comme

public class SharedViewModel extends ViewModel {
private MutableLiveData<CharSequence>text = new MutableLiveData<>();

public void setText(CharSequence input)
{
    text.setValue(input);
}

public LiveData<CharSequence> getText(){
    return text;

}
}

Livetaa est utilisé dans des fragments comme

private SharedViewModel viewModel;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //No Need to initate further
        viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        viewModel.getText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
            @Override
            public void onChanged(@Nullable CharSequence charSequence) {
                editText.setText(charSequence);
            }
        });
    }

en classe de fragments soit comme

public class FragmentA extends Fragment {
    private SharedViewModel viewModel;
    private EditText editText;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_a, container, false);
        editText = v.findViewById(R.id.edit_text);
        Button button = v.findViewById(R.id.button_ok);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.setText(editText.getText());
            }
        });
        return v;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        viewModel.getText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
            @Override
            public void onChanged(@Nullable CharSequence charSequence) {
                editText.setText(charSequence);
            }
        });
    }
}
0
pankaj jha