【问题标题】:onChanged is never called when getting data from Firebase using LiveData使用 LiveData 从 Firebase 获取数据时永远不会调用 onChanged
【发布时间】:2019-09-03 11:45:59
【问题描述】:

我有以下活动类:

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        splashViewModel.nameLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String name) {
                Log.d(TAG, name); //Isn't printing anything
            }
        });
    }
}

这是我的视图模型类:

public class SplashViewModel extends ViewModel {
    private SplashRepository repository;
    MutableLiveData<String> nameLiveData;

    @Inject
    SplashViewModel(SplashRepository repository) {
        this.repository = repository;
        nameLiveData = repository.addNameToLiveData();
    }
}

这是我的存储库类:

class SplashRepository {
    MutableLiveData<String> addNameToLiveData() {
        MutableLiveData<String> nameMutableLiveData = new MutableLiveData<>();
        ref.document(uid).get().addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if(document.exists()) {
                    String name = document.getString("name");
                    Log.d(TAG, name); //Is printed out correctly
                    nameMutableLiveData.postValue(name);
                }
            }
        });
        return nameMutableLiveData;
    }
}

我正在使用postValue() 将数据添加到LiveData。在回调中,它正确打印了名称,但是在观察nameLiveData 对象时,甚至没有触发onChanged。如何解决?

【问题讨论】:

  • 您需要在 ViewModel 上观察 nameMutableLiveData 或使用 onCompletion 接口返回字符串名称的值。您在收到 Firebase 的响应之前返回 LiveData,这是一个异步调用,因此没有任何发布价值的意义。
  • @Shermano 这不是我在做什么,使用splashViewModel.nameLiveData.observe(...) 观察nameMutableLiveData 对象吗?其次,我会尽快在回调中发布该值。有没有其他办法?
  • 我感觉这样不行,你应该改用 MeaditorLiveData,但我不太确定,也许有人可以更好地帮助你,干杯
  • 你说我应该使用MediatorLiveData而不是MutableLiveData?刚刚遇到了同样的问题。

标签: android firebase google-cloud-firestore android-livedata android-viewmodel


【解决方案1】:

Repos 应该具有不可变和可变的实时数据对象。Repo 应该公开不可变的实时数据对象,这些数据对象将使用 observeforever 方法在视图模型中观察。 非可变对象使用可变对象进行更新。 示例应用示例

https://github.com/ashok07m/Pokemon-Sample-App/blob/master/app/src/main/java/com/learning/pokemon/data/repository/MainRepositoryImpl.kt

【讨论】:

  • 感谢您的回答,但我仍然很困惑。你说的我该怎么做?
  • 查看示例链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多