【问题标题】:How to fix "Required MutableLiveData<String> but 'SwitchMap' was inferred to LiveData<Y>" when using Transformations.switchMap?使用 Transformations.switchMap 时,如何修复“必需的 MutableLiveData<String> 但 'SwitchMap' 被推断为 LiveData<Y>”?
【发布时间】:2018-12-27 04:29:14
【问题描述】:

我正在尝试将 ViewModel 与一些 LiveData 一起使用,该 LiveData 使用来自另一个 LiveData 的值。

为此,我正在尝试使用Transformations.switchMap,但我得到了

不兼容的类型。需要 MutableLiveData 但 'switchMap' 被推断为 LiveData:没有类型变量的实例 Y 存在以便 LiveData 符合 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 的值,但我做不到。

【问题讨论】:

    标签: android android-livedata switchmap


    【解决方案1】:

    基本上,Transformations.switchMap 返回LiveData,而您的接收者类型是MutableLiveData。考虑改变如下:

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

    检查reference

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      相关资源
      最近更新 更多