86 lines
3.0 KiB
Java
86 lines
3.0 KiB
Java
package com.gh.gamecenter.collection;
|
|
|
|
import android.app.Application;
|
|
import androidx.lifecycle.LiveData;
|
|
import androidx.annotation.NonNull;
|
|
|
|
import com.gh.common.history.HistoryDatabase;
|
|
import com.gh.gamecenter.baselist.ListViewModel;
|
|
import com.gh.gamecenter.entity.NewsEntity;
|
|
import com.gh.gamecenter.entity.ViewsEntity;
|
|
import com.gh.gamecenter.info.NewsViewsRepository;
|
|
import com.gh.gamecenter.manager.UserManager;
|
|
import com.gh.gamecenter.retrofit.RetrofitManager;
|
|
|
|
import java.util.List;
|
|
|
|
import io.reactivex.Observable;
|
|
import io.reactivex.Single;
|
|
|
|
/**
|
|
* Created by khy on 30/03/18.
|
|
*/
|
|
|
|
public class ArticleViewModel extends ListViewModel<NewsEntity, NewsEntity> {
|
|
|
|
public ArticleFragment.Type type;
|
|
|
|
NewsViewsRepository<ViewsEntity> mNewsViewsRepository = new NewsViewsRepository<>();
|
|
|
|
public ArticleViewModel(@NonNull Application application) {
|
|
super(application);
|
|
mResultLiveData.addSource(mListLiveData, list -> {
|
|
if (list == null) return;
|
|
mResultLiveData.postValue(NewsEntity.Companion.deepCopy(list));
|
|
StringBuilder builder = new StringBuilder();
|
|
for (int i = 0; i < list.size(); i++) {
|
|
NewsEntity newsEntity = list.get(i);
|
|
if (newsEntity.getViews() == 0) {
|
|
builder.append(newsEntity.getId());
|
|
builder.append("-");
|
|
}
|
|
}
|
|
|
|
if (builder.length() > 0) {
|
|
builder.deleteCharAt(builder.length() - 1);
|
|
String ids = builder.toString();
|
|
mNewsViewsRepository.getNewsViews(RetrofitManager.getInstance(getApplication()).getData().getNewsViews(ids));
|
|
}
|
|
});
|
|
|
|
LiveData<List<ViewsEntity>> listLiveData = mNewsViewsRepository.asLiveData();
|
|
mResultLiveData.addSource(listLiveData, viewsEntities -> {
|
|
List<NewsEntity> value = mListLiveData.getValue();
|
|
if (value != null && viewsEntities != null)
|
|
for (ViewsEntity viewsEntity : viewsEntities) {
|
|
for (NewsEntity newsEntity : value) {
|
|
if (viewsEntity.getId().equals(newsEntity.getId())) {
|
|
newsEntity.setViews(viewsEntity.getViews());
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
mResultLiveData.postValue(NewsEntity.Companion.deepCopy(value));
|
|
});
|
|
}
|
|
|
|
@Override
|
|
protected void mergeResultLiveData() {
|
|
|
|
}
|
|
|
|
@Override
|
|
public Single<List<NewsEntity>> provideDataSingle(int page) {
|
|
if (type == ArticleFragment.Type.COLLECTION) {
|
|
return Single.fromObservable(RetrofitManager.getInstance(getApplication()).getApi().getCollectionArticle(UserManager.getInstance().getUserId(), page));
|
|
} else {
|
|
return HistoryDatabase.Companion.getInstance().newsDao().getNewsWithOffset(20, (page - 1) * 20);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public Observable<List<NewsEntity>> provideDataObservable(int page) {
|
|
return null;
|
|
}
|
|
}
|