我正在尝试将 ViewModel 与某些 LiveData 一起使用,这些 LiveData 使用另一个 LiveData 的值。
为此,我尝试使用 Transformations.switchMap
但我得到了
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
我已经尝试切换到 Transformations.map
,但结果相同。
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);}
}
我希望 userId 依赖于 userLiveData 的值,但我做不到。
最佳答案
基本上,当您的接收器类型为 MutableLiveData
时,Transformations.switchMap
返回 LiveData
。考虑进行如下更改:
private final LiveData<String> userId = Transformations.switchMap(userLiveData, input -> {
return input.getUid();
}); // Here we change userId 'MutableLiveData' to 'LiveData'.
检查reference .
关于android - 使用 Transformations.switchMap 时如何修复 "Required MutableLiveData<String> but ' SwitchMap' 被推断为 LiveData<Y>"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53939760/