4

I am trying to use ViewModel with some LiveData that uses the value from another LiveData.

For that I am trying to use Transformations.switchMap but I am getting

Incompatible types. Required MutableLiveData but 'switchMap' was inferred to LiveData: no instance(s) of type variable(s) Y exist so that LiveData conforms to MutableLiveData

I have already tried to switch to Transformations.map, but with the same results.

public class RestaurantViewModel extends ViewModel {

    private MutableLiveData<FirebaseUser> userLiveData  = new MutableLiveData<>();

    private final MutableLiveData<String> userId =
    Transformations.switchMap(userLiveData, input -> {
        return input.getUid();
    });

    private String getUid(FirebaseUser user){
        return user.getUid();
    }

    private void setUser(FirebaseUser currentUser){
        this.userLiveData.setValue(currentUser);}
}

I expected the userId to be dependent on the value of userLiveData, but I am can't do it.

daedsidog
  • 1,732
  • 2
  • 17
  • 36

1 Answers1

4

Basically, Transformations.switchMap returns LiveData while your receiver type is MutableLiveData. consider changing like below :

private final LiveData<String> userId = Transformations.switchMap(userLiveData, input -> {
    return input.getUid();
}); // Here we change userId 'MutableLiveData' to 'LiveData'.

Check reference.

Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58