android.support.v7.util.DiffUtil Java Examples

The following examples show how to use android.support.v7.util.DiffUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RepositoryPresentersTest.java    From agera with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotifyFineGrainedEventsWithDiffWithMoveDetection() {
  final List<String> oldData = asList("A:1", "B:2", "C:3", "D:0");
  final List<String> newData = asList("B:2", "D:0", "A:4", "C:5");
  final DiffingLogic diffingLogic = new DiffingLogic(oldData, newData);
  final RepositoryPresenter<List<String>> diffingPresenter =
      repositoryPresenterOf(String.class)
          .layout(LAYOUT_ID)
          .bindCollectionWith(Binders.<List<String>, View>nullBinder()) // restricts to collection
          .diffWith(diffingLogic, true)                            // to test compiling this line.
          .forCollection(Functions.<List<String>>identityFunction());

  final boolean fineGrained = diffingPresenter.getUpdates(oldData, newData, listUpdateCallback);

  assertThat(fineGrained, is(true));
  DiffUtil.calculateDiff(diffingLogic, true).dispatchUpdatesTo(
      verifyingWrapper(listUpdateCallback));
  verifyNoMoreInteractions(listUpdateCallback);
}
 
Example #2
Source File: RepositoryPresentersTest.java    From agera with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotifyFineGrainedEventsWithDiffWith() {
  final List<String> oldData = asList("A:1", "B:2", "C:3");
  final List<String> newData = asList("B:2", "A:4", "C:5");
  final DiffingLogic diffingLogic = new DiffingLogic(oldData, newData);
  final RepositoryPresenter<List<String>> diffingPresenter =
      repositoryPresenterOf(String.class)
          .layout(LAYOUT_ID)
          .diffWith(diffingLogic, false)
          .forList();

  final boolean fineGrained = diffingPresenter.getUpdates(oldData, newData, listUpdateCallback);

  assertThat(fineGrained, is(true));
  DiffUtil.calculateDiff(diffingLogic, false).dispatchUpdatesTo(
      verifyingWrapper(listUpdateCallback));
  verifyNoMoreInteractions(listUpdateCallback);
}
 
Example #3
Source File: DataBindingRepositoryPresentersTest.java    From agera with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotifyFineGrainedEventsWithDiffWithMoveDetection() {
  final List<String> oldData = asList("A:1", "B:2", "C:3", "D:0");
  final List<String> newData = asList("B:2", "D:0", "A:4", "C:5");
  final DiffingLogic diffingLogic = new DiffingLogic(oldData, newData);
  final RepositoryPresenter<List<String>> diffingPresenter =
      dataBindingRepositoryPresenterOf(String.class)
          .layout(LAYOUT_ID)
          .itemId(ITEM_ID)
          .diffWith(diffingLogic, true)
          .forCollection(Functions.<List<String>>identityFunction());

  final boolean fineGrained = diffingPresenter.getUpdates(oldData, newData, listUpdateCallback);

  assertThat(fineGrained, is(true));
  DiffUtil.calculateDiff(diffingLogic, true).dispatchUpdatesTo(
      verifyingWrapper(listUpdateCallback));
  verifyNoMoreInteractions(listUpdateCallback);
}
 
Example #4
Source File: DataBindingRepositoryPresentersTest.java    From agera with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotifyFineGrainedEventsWithDiffWith() {
  final List<String> oldData = asList("A:1", "B:2", "C:3");
  final List<String> newData = asList("B:2", "A:4", "C:5");
  final DiffingLogic diffingLogic = new DiffingLogic(oldData, newData);
  final RepositoryPresenter<List<String>> diffingPresenter =
      dataBindingRepositoryPresenterOf(String.class)
          .layout(LAYOUT_ID)
          .itemId(ITEM_ID)
          .diffWith(diffingLogic, false)
          .forList();

  final boolean fineGrained = diffingPresenter.getUpdates(oldData, newData, listUpdateCallback);

  assertThat(fineGrained, is(true));
  DiffUtil.calculateDiff(diffingLogic, false).dispatchUpdatesTo(
      verifyingWrapper(listUpdateCallback));
  verifyNoMoreInteractions(listUpdateCallback);
}
 
Example #5
Source File: HistoryFragment.java    From iroha-android with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_history, container, false);
    SampleApplication.instance.getApplicationComponent().inject(this);

    presenter.setFragment(this);
    presenter.onCreateView();
    presenter.getTransactions();

    TransactionsViewModel transactionsViewModel = ViewModelProviders.of(this).get(TransactionsViewModel.class);
    transactionsViewModel.getTransactions().observe(this, transactions -> {
        DiffUtil.Callback transactionDiffChecker =
                new TransactionDiffChecker(adapter.getTransactions(), transactions);
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(transactionDiffChecker);
        adapter.setTransactions(transactions);
        diffResult.dispatchUpdatesTo(adapter);
    });

    configureRecycler();
    binding.refresh.setOnRefreshListener(() -> presenter.getTransactions());
    return binding.getRoot();
}
 
Example #6
Source File: CommonPresenter.java    From JReadHub with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void getDiffResult(List<NewsBean> oldData, List<NewsBean> newData) {
    addSubscribe(Observable.just(DiffUtil.calculateDiff(new DiffCallback(oldData, newData), false))
            .subscribeWith(new DisposableObserver<DiffUtil.DiffResult>() {
                @Override
                public void onNext(DiffUtil.DiffResult diffResult) {
                    getView().onDiffResult(diffResult, newData);
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            }));
}
 
Example #7
Source File: MjolnirRecyclerAdapter.java    From MjolnirRecyclerView with Apache License 2.0 6 votes vote down vote up
/**
 * Dispatched {@param diffResult} DiffResults to the adapter if adapter has not been cancelled. If there are any queued pending updates,
 * it will peek the latest new items collection and once again update the adapter content.
 *
 * @param newItems   Collection of new items, with which our current items collection is updated.
 * @param diffResult DiffUtil.DiffResult which was calculated for {@param callback}.
 * @param callback   DiffUtil.Callback on which DiffResult was calculated.
 */
private void postDiffResults(final Collection<E> newItems, final DiffUtil.DiffResult diffResult, final DiffUtil.Callback callback) {
    if (!isCancelled) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                pendingUpdates.remove();
                diffResult.dispatchUpdatesTo(MjolnirRecyclerAdapter.this);
                items.clear();
                items.addAll(newItems);

                if (pendingUpdates.size() > 0) {
                    updateData(pendingUpdates.peek(), callback);
                }
            }
        });
    }
}
 
Example #8
Source File: TopicPresenter.java    From JReadHub with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void getDiffResult(List<TopicBean> oldData, List<TopicBean> newData) {
    addSubscribe(Observable.just(DiffUtil.calculateDiff(new DiffCallback(oldData, newData), false))
            .subscribeWith(new DisposableObserver<DiffUtil.DiffResult>() {
                @Override
                public void onNext(DiffUtil.DiffResult diffResult) {
                    getView().onDiffResult(diffResult, newData);
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            }));
}
 
Example #9
Source File: OnlyAdapter.java    From NoAdapter with Apache License 2.0 6 votes vote down vote up
public void setItems(final List<?> newItems) {
  cancelUpdateTask();
  dataVersion++;
  if (items == null) {
    if (newItems == null) {
      return;
    }
    items = new ArrayList<>(newItems);
    notifyDataSetChanged();
  } else if (newItems == null) {
    int oldSize = items.size();
    items = null;
    notifyItemRangeRemoved(0, oldSize);
  } else {
    final List<?> oldItems = items;
    int maxItemCount = newItems.size() > oldItems.size() ? newItems.size() : oldItems.size();
    if (maxItemCount < 50) {
      // we don't need to calculate in background for less than 100 items.
      final DiffUtil.DiffResult diffResult = calculateDiff(oldItems, newItems, diffCallback);
      postUpdate(newItems, diffResult);
    } else {
      updateTask = new UpdateTask(oldItems, newItems, diffCallback, this).execute();
    }
  }
}
 
Example #10
Source File: RecyclerViewAdapter.java    From journaldev with MIT License 5 votes vote down vote up
public void setData(ArrayList<Model> newData) {

        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new MyDiffUtilCallBack(newData, data));
        diffResult.dispatchUpdatesTo(this);
        data.clear();
        this.data.addAll(newData);
    }
 
Example #11
Source File: StringRequestFragment.java    From VolleyX with Apache License 2.0 5 votes vote down vote up
void refreshItems() {
    final StringRequest request = new StringRequest(URL, null, null);
    VolleyX.from(request).subscribeOn(Schedulers.io())
            .map(new Func1<String, List<Music>>() {
                @Override
                public List<Music> call(String s) {
                    return mapper.transformJsonToMusicCollection(s);
                }
            }).map(new Func1<List<Music>, Pair<DiffUtil.DiffResult, List<Music>>>() {
                @Override
                public Pair<DiffUtil.DiffResult, List<Music>> call(List<Music> musics) {
                    return Pair.create(DiffUtil.calculateDiff(new MusicListDiffCallback(mAdapter.getDatas(), musics)), musics);
                }
            }).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<Pair<DiffUtil.DiffResult, List<Music>>>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "onCompleted");
                    mSwipeRefreshLayout.setRefreshing(false);
                }

                @Override
                public void onError(Throwable e) {
                    Log.d(TAG, "onError " + Log.getStackTraceString(e));
                    mSwipeRefreshLayout.setRefreshing(false);
                }

                @Override
                public void onNext(Pair<DiffUtil.DiffResult, List<Music>> result) {
                    Log.d(TAG, "onNext");
                    mAdapter.setDatas(result.second);
                    result.first.dispatchUpdatesTo(mAdapter);
                }
            });
}
 
Example #12
Source File: MjolnirRecyclerAdapter.java    From MjolnirRecyclerView with Apache License 2.0 5 votes vote down vote up
/**
 * Update the current adapter state. If {@param callback} is provided, an updated data set is calculated with DiffUtil, otherwise
 * current data set is clear and {@param newItems} are added to the internal items collection.
 *
 * @param newItems Collection of new items, which are added to adapter.
 * @param callback DiffUtil callback, which is used to update the items.
 */
public void update(Collection<E> newItems, @Nullable DiffUtil.Callback callback) {
    if (callback != null) {
        pendingUpdates.add(newItems);
        if (pendingUpdates.size() == 1) {
            updateData(newItems, callback);
        }
    } else {
        items.clear();
        items.addAll(newItems);
        notifyDataSetChanged();
    }
}
 
Example #13
Source File: MjolnirRecyclerAdapter.java    From MjolnirRecyclerView with Apache License 2.0 5 votes vote down vote up
/**
 * Calculates provided {@param callback} DiffResult by using DiffUtils.
 *
 * @param newItems Collection of new items, with which our current items collection is updated.
 * @param callback DiffUtil.Callback on which DiffResult is calculated.
 */
private void updateData(final Collection<E> newItems, final DiffUtil.Callback callback) {
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(callback);
            postDiffResults(newItems, diffResult, callback);
        }
    });
}
 
Example #14
Source File: OnlyAdapter.java    From NoAdapter with Apache License 2.0 5 votes vote down vote up
@NonNull
private static DiffUtil.DiffResult calculateDiff(
    List<?> oldItems,
    List<?> update,
    DiffCallback diffCallback) {
  return DiffUtil.calculateDiff(new DiffUtilCallback(oldItems, update, diffCallback));
}
 
Example #15
Source File: OnlyAdapter.java    From NoAdapter with Apache License 2.0 5 votes vote down vote up
@Override
protected void onPostExecute(DiffUtil.DiffResult diffResult) {
  final OnlyAdapter onlyAdapter = adapterRef.get();
  if (onlyAdapter == null || onlyAdapter.dataVersion != dataVersion) {
    return;
  }
  onlyAdapter.postUpdate(newItems, diffResult);
}
 
Example #16
Source File: MixedContentAdapter.java    From Anecdote with Apache License 2.0 5 votes vote down vote up
@Override
public void setData(final List<Anecdote> quotes) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(
                new AnecdoteListDiffCallback(
                        mAnecdotes,
                        quotes)
        );

        if (!mAnecdotes.isEmpty()) {
            mAnecdotes.clear();
            mAnecdotes.addAll(quotes);
            diffResult.dispatchUpdatesTo(this);
        } else {
            // Prevent recyclerView follow the loading wheel when first items are just added
            mAnecdotes.addAll(quotes);
            this.notifyDataSetChanged();
        }

    } else {
        // Run this on main thread
        Handler mainHandler = new Handler(Looper.getMainLooper());
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                MixedContentAdapter.this.setData(quotes);
            }
        };
        mainHandler.post(runnable);
    }
}
 
Example #17
Source File: ChecklistAdapter.java    From Travel-Mate with MIT License 5 votes vote down vote up
void updateChecklist(List<ChecklistItem> items) {
    ChecklistItemDiffCallback diffCallback = new ChecklistItemDiffCallback(mItems, items);
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
    mItems.clear();
    mItems.addAll(items);
    // this handles all updates, so we don't need manual notifyItem* calls
    diffResult.dispatchUpdatesTo(ChecklistAdapter.this);

    if (mCanAddItems) checkLastItem();
}
 
Example #18
Source File: MainActivity.java    From rxSuggestions with Apache License 2.0 5 votes vote down vote up
void setSuggestions(@NonNull List<String> newStrings) {
    final SuggestionDiff suggestionDiff = new SuggestionDiff(suggestions, newStrings);
    final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(suggestionDiff, true);
    suggestions.clear();
    suggestions.addAll(newStrings);
    diffResult.dispatchUpdatesTo(this);
}
 
Example #19
Source File: HoverMenu.java    From hover with Apache License 2.0 5 votes vote down vote up
public void notifyMenuChanged() {
    List<Section> oldSections = mSections;
    List<Section> newSections = getSections();
    mSections = newSections;

    if (null != mListUpdateCallback) {
        DiffUtil.Callback diffCallback = new MenuDiffCallback(oldSections, newSections);
        // calculateDiff() can be long-running.  We let it run synchronously because we don't
        // expect many Sections.
        DiffUtil.DiffResult result = DiffUtil.calculateDiff(diffCallback, true);
        result.dispatchUpdatesTo(mListUpdateCallback);
    }
}
 
Example #20
Source File: TradeMaterialsAdapter.java    From settlers-remake with MIT License 5 votes vote down vote up
public void setMaterialStates(List<TradeMaterialState> tradeMaterialStates) {
	if (this.tradeMaterialStates != null) {
		DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new MaterialsDiffCallback(this.tradeMaterialStates, tradeMaterialStates));
		diffResult.dispatchUpdatesTo(this);
	}

	this.tradeMaterialStates = tradeMaterialStates;
}
 
Example #21
Source File: MaterialsAdapter.java    From settlers-remake with MIT License 5 votes vote down vote up
public void setMaterialStates(List<StockMaterialState> materialStates) {
	if (this.materialStates != null) {
		DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new MaterialsDiffCallback(this.materialStates, materialStates));
		diffResult.dispatchUpdatesTo(this);
	}

	this.materialStates = materialStates;
}
 
Example #22
Source File: MultiTypeAdapter.java    From Word-Search-Game with GNU General Public License v3.0 5 votes vote down vote up
public <T> void setItems(List<T> models) {
    mCallback.set(mData, (List<Object>) models);
    DiffUtil.DiffResult result = DiffUtil.calculateDiff(mCallback);
    result.dispatchUpdatesTo(this);
    mData.clear();
    mData.addAll(models);
}
 
Example #23
Source File: MoviesAdapter.java    From YTS with MIT License 5 votes vote down vote up
public void updateData(List<BaseMovie.Movie> movieList, boolean newList) {
  if (newList) {
    DiffUtil.DiffResult result = DiffUtil.calculateDiff(
        new MoviesDiffCallback(this.movieList, movieList)
    );
    this.movieList.clear();
    result.dispatchUpdatesTo(this);
  }
  this.movieList.addAll(movieList);
  if (!newList) notifyItemRangeInserted(getItemCount(), this.movieList.size() - 1);
}
 
Example #24
Source File: EntityAdapter.java    From homeassist with Apache License 2.0 5 votes vote down vote up
public void updateList(ArrayList<Entity> newItems) {
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new EntityDiffUtilCallback(getDisplayItems(), newItems));
    this.items.clear();
    this.items.addAll(newItems);

    if (isFilterState()) {
        for (Entity item : items) {
            int filterpos = filteredItems.indexOf(item);
            if (filterpos != -1) {
                filteredItems.set(filterpos, item);
            }
        }
    }
    diffResult.dispatchUpdatesTo(this);
}
 
Example #25
Source File: NotesListAdapter.java    From RoomDb-Sample with Apache License 2.0 5 votes vote down vote up
public void addTasks(List<Note> newNotes) {
    NoteDiffUtil noteDiffUtil = new NoteDiffUtil(notes, newNotes);
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(noteDiffUtil);
    notes.clear();
    notes.addAll(newNotes);
    diffResult.dispatchUpdatesTo(this);
}
 
Example #26
Source File: EntityAdapter.java    From homeassist with Apache License 2.0 5 votes vote down vote up
public void updateDisplayList(ArrayList<Entity> newItems) {
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new EntityDiffUtilCallback(getDisplayItems(), newItems));

    if (isFilterState()) {
        this.filteredItems = new ArrayList<>();
        this.filteredItems.clear();
        this.filteredItems.addAll(newItems);
    } else {
        this.items.clear();
        this.items.addAll(newItems);
    }
    diffResult.dispatchUpdatesTo(this);
}
 
Example #27
Source File: EntityAdapter.java    From homeassist with Apache License 2.0 5 votes vote down vote up
public void clearFilter() {
    if (filteredItems != null) {
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new EntityDiffUtilCallback(getDisplayItems(), items));
        filteredItems = null;
        diffResult.dispatchUpdatesTo(this);
    }
}
 
Example #28
Source File: EntityAdapter.java    From homeassist with Apache License 2.0 5 votes vote down vote up
public void updateFilterList(ArrayList<Entity> newItems) {

        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new EntityDiffUtilCallback(getDisplayItems(), newItems));

        if (filteredItems == null) {
            filteredItems = new ArrayList<>();
        }
        this.filteredItems.clear();
        this.filteredItems.addAll(newItems);
        diffResult.dispatchUpdatesTo(this);
    }
 
Example #29
Source File: LogbookActivity.java    From homeassist with Apache License 2.0 5 votes vote down vote up
public void setItems(List<LogSheet> newItems) {
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new LogSheetDiffUtilCallback(items, newItems));
    this.items.clear();
    this.items.addAll(newItems);
    diffResult.dispatchUpdatesTo(this);
    //this.items = items;
    //notifyDataSetChanged();
}
 
Example #30
Source File: RecentMsgFragment.java    From Tok-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void showRecentMsg(DiffUtil.DiffResult result, List<ConversationItem> conversationList) {
    mConversationList = conversationList;
    LogUtil.i(TAG, "showRecentMsg");
    if (mRecentMsgAdapter == null) {
        mRecentMsgAdapter = new RecentMsgAdapter(getActivity());
        mRecentMsgRv.setAdapter(mRecentMsgAdapter);
        mRecentMsgAdapter.setItemClickListener(this);
        mRecentMsgAdapter.setItemLongClickListener(this);
    }
    mRecentMsgAdapter.updateDataList(mConversationList);
    result.dispatchUpdatesTo(mRecentMsgAdapter);
}