user1785730
user1785730

Reputation: 3535

Compilation error trying to communicate between Fragments with ViewModel

I followed this guide to implement communication between fragments. This is the relevant code from the guide:

    SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
    model.getSelected().observe(getViewLifecycleOwner(), { item ->
       // Update the UI.
    });

My actual code looks like this:

    HeaderViewModel model = new ViewModelProvider(requireActivity()).get(HeaderViewModel.class);
    TextView year = view.findViewById(R.id.year_text);
    model.getYear().observe(getViewLifecycleOwner(), { item -> year.setText(item) });

And this is the error I get:

error: illegal start of expression
    model.getYear().observe(getViewLifecycleOwner(), { item -> year.setText(item) });
                                                     ^

Why? What does this mean? How to fix it?

Upvotes: 0

Views: 29

Answers (1)

Bö macht Blau
Bö macht Blau

Reputation: 13009

It looks like you stumbled across a typo in the documentation: the snippet you used is syntactically wrong, it should be

model.getYear().observe(getViewLifecycleOwner(), item -> {year.setText(item)});

Right above the buggy example there is another snippet with another lambda expression which shows how to do it correctly:

public class MasterFragment extends Fragment {
    private SharedViewModel model;

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {
            model.select(item);
        });
    }
}

Upvotes: 1

Related Questions