好的,所以我找到了解决方案,尽管我不知道为什么会这样。
还记得我说过“不要担心同步方法”吗?嗯...事实证明它有一些问题,这进一步延迟了解决方案。
我认为最重要的错误是当网络响应到来时更新数据库中的对象的方法。
我以前打电话
@Update
void update(Form form)
在 dao 中,由于未知原因,它不会触发 LiveData-Observer。所以我把它改为
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Form form);
完成此操作后,我可以从我的存储库中获取 Form-LiveData,就像
LiveData<List<Form>> liveData = formRepository.allForms();
然后像往常一样订阅它。
之前失败的测试现在看起来像这样:
@Test
public void shouldSaveFormsFromServerIntoDb() throws Exception
{
Lifecycle lifecycle = Mockito.mock(Lifecycle.class);
when(lifecycle.getCurrentState()).thenReturn(Lifecycle.State.RESUMED);
LifecycleOwner owner = Mockito.mock(LifecycleOwner.class);
when(owner.getLifecycle()).thenReturn(lifecycle);
final CountDownLatch l = new CountDownLatch(19);
final SortedList<Form> sortedForms = new SortedList<Form>(Form.class, new SortedList.Callback<Form>()
{
@Override
public int compare(Form o1, Form o2)
{
return o1.getUniqueId().compareTo(o2.getUniqueId());
}
@Override
public void onChanged(int position, int count)
{
Log.d(LOG_TAG, "onChanged: Form at position " + position + " has changed. Count is " + count);
for (int i = 0; i < count; i++)
{
l.countDown();
}
}
@Override
public boolean areContentsTheSame(Form oldItem, Form newItem)
{
return (oldItem.getContent() != null && newItem.getContent() != null && oldItem.getContent().equals(newItem.getContent())) || oldItem.getContent() == null && newItem.getContent() == null;
}
@Override
public boolean areItemsTheSame(Form item1, Form item2)
{
return item1.getUniqueId().equals(item2.getUniqueId());
}
@Override
public void onInserted(int position, int count)
{
}
@Override
public void onRemoved(int position, int count)
{
}
@Override
public void onMoved(int fromPosition, int toPosition)
{
}
});
LiveData<List<Form>> ld = formRepository.allForms();
ld.observe(owner, formList ->
{
if (formList != null && !formList.isEmpty())
{
Log.d(LOG_TAG, "shouldSaveFormsFromServerIntoDb: List contains " + sortedForms.size() + " Forms");
sortedForms.addAll(formList);
}
});
formRepository.synchronizeFormsWithServer(owner);
l.await(2, TimeUnit.MINUTES);
assertEquals(0, l.getCount());
}
我知道将从服务器获取 19 个表单,然后每个表单都会更改一次(第一次加载包含所有数据减少的表单的列表,第二次我再次从服务器加载每个项目,替换旧值)在数据库中具有更多数据的新值)。
我不知道这是否会对您有帮助@joao86,但也许您有类似的问题。如果是这样,请务必在这里发表评论:)