Start migrating to Paging 3 library.

This commit is contained in:
Alex Ning 2021-09-05 23:42:53 +08:00
parent 38caf7365a
commit ba2c12d45d
14 changed files with 750 additions and 4830 deletions

View File

@ -34,9 +34,6 @@
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:replace="android:label">
<activity
android:name=".activities.Paging3TestActivity"
android:exported="true" />
<activity
android:name=".activities.WikiActivity"
android:label="@string/wiki_activity_label"

View File

@ -25,7 +25,6 @@ import ml.docilealligator.infinityforreddit.activities.LockScreenActivity;
import ml.docilealligator.infinityforreddit.activities.LoginActivity;
import ml.docilealligator.infinityforreddit.activities.MainActivity;
import ml.docilealligator.infinityforreddit.activities.MultiredditSelectionActivity;
import ml.docilealligator.infinityforreddit.activities.Paging3TestActivity;
import ml.docilealligator.infinityforreddit.activities.PostFilterPreferenceActivity;
import ml.docilealligator.infinityforreddit.activities.PostFilterUsageListingActivity;
import ml.docilealligator.infinityforreddit.activities.PostGalleryActivity;
@ -287,6 +286,4 @@ public interface AppComponent {
void inject(WikiActivity wikiActivity);
void inject(Infinity infinity);
void inject(Paging3TestActivity paging3TestActivity);
}

View File

@ -46,17 +46,6 @@ class AppModule {
@Named("oauth")
@Singleton
Retrofit provideOauthRetrofit(@Named("default") OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.baseUrl(APIUtils.OAUTH_API_BASE_URI)
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
}
@Provides
@Named("paging_3_test")
@Singleton
Retrofit providePaging3TestRetrofit(@Named("default") OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.baseUrl(APIUtils.OAUTH_API_BASE_URI)
.client(okHttpClient)
@ -82,6 +71,7 @@ class AppModule {
return new Retrofit.Builder()
.baseUrl(APIUtils.API_BASE_URI)
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(GuavaCallAdapterFactory.create())
.build();
}

View File

@ -729,10 +729,8 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
}
break;
default:
Intent intent = new Intent(this, Paging3TestActivity.class);
startActivity(intent);
/*PostTypeBottomSheetFragment postTypeBottomSheetFragment = new PostTypeBottomSheetFragment();
postTypeBottomSheetFragment.show(getSupportFragmentManager(), postTypeBottomSheetFragment.getTag());*/
PostTypeBottomSheetFragment postTypeBottomSheetFragment = new PostTypeBottomSheetFragment();
postTypeBottomSheetFragment.show(getSupportFragmentManager(), postTypeBottomSheetFragment.getTag());
break;
}
});

View File

@ -1,169 +0,0 @@
package ml.docilealligator.infinityforreddit.activities;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.DisplayMetrics;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import androidx.transition.AutoTransition;
import androidx.transition.TransitionManager;
import java.util.Locale;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import im.ene.toro.exoplayer.ExoCreator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SortType;
import ml.docilealligator.infinityforreddit.adapters.Paging3TestAdapter;
import ml.docilealligator.infinityforreddit.customtheme.CustomThemeWrapper;
import ml.docilealligator.infinityforreddit.fragments.PostFragment;
import ml.docilealligator.infinityforreddit.post.PostDataSource;
import ml.docilealligator.infinityforreddit.post.PostPaging3ViewModel;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
public class Paging3TestActivity extends BaseActivity {
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("paging_3_test")
Retrofit mPaging3Retrofit;
@Inject
@Named("gfycat")
Retrofit mGfycatRetrofit;
@Inject
@Named("redgifs")
Retrofit mRedgifsRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
@Named("post_layout")
SharedPreferences mPostLayoutSharedPreferences;
@Inject
@Named("nsfw_and_spoiler")
SharedPreferences mNsfwAndSpoilerSharedPreferences;
@Inject
@Named("post_history")
SharedPreferences mPostHistorySharedPreferences;
@Inject
@Named("post_feed_scrolled_position_cache")
SharedPreferences mPostFeedScrolledPositionSharedPreferences;
@Inject
@Named("current_account")
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
@Named("sort_type")
SharedPreferences mSortTypeSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
ExoCreator mExoCreator;
@Inject
Executor mExecutor;
public PostPaging3ViewModel viewModel;
private Paging3TestAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
((Infinity) getApplication()).getAppComponent().inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paging3_test);
String accessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
String accountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
int defaultPostLayout = Integer.parseInt(mSharedPreferences.getString(SharedPreferencesUtils.DEFAULT_POST_LAYOUT_KEY, "0"));
boolean savePostFeedScrolledPosition = mSharedPreferences.getBoolean(SharedPreferencesUtils.SAVE_FRONT_PAGE_SCROLLED_POSITION, false);
boolean rememberMutingOptionInPostFeed = mSharedPreferences.getBoolean(SharedPreferencesUtils.REMEMBER_MUTING_OPTION_IN_POST_FEED, false);
Locale locale = getResources().getConfiguration().locale;
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int windowWidth = displayMetrics.widthPixels;
int postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_FRONT_PAGE_POST, defaultPostLayout);
int postType = PostDataSource.TYPE_FRONT_PAGE;
String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_BEST_POST, SortType.Type.BEST.name());
SortType sortType;
if (sort.equals(SortType.Type.CONTROVERSIAL.name()) || sort.equals(SortType.Type.TOP.name())) {
String sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_BEST_POST, SortType.Time.ALL.name());
sortType = new SortType(SortType.Type.valueOf(sort), SortType.Time.valueOf(sortTime));
} else {
sortType = new SortType(SortType.Type.valueOf(sort));
}
RecyclerView recyclerView = findViewById(R.id.recycler_view);
adapter = new Paging3TestAdapter(this, new PostFragment(), mExecutor,
mOauthRetrofit, mGfycatRetrofit,
mRedgifsRetrofit, mCustomThemeWrapper, locale,
windowWidth, accessToken, accountName, postType, postLayout, true,
mSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences,
mExoCreator, new Paging3TestAdapter.Callback() {
@Override
public void retryLoadingMore() {
}
@Override
public void typeChipClicked(int filter) {
}
@Override
public void flairChipClicked(String flair) {
}
@Override
public void nsfwChipClicked() {
}
@Override
public void currentlyBindItem(int position) {
}
@Override
public void delayTransition() {
TransitionManager.beginDelayedTransition(recyclerView, new AutoTransition());
}
});
recyclerView.setAdapter(adapter);
viewModel = new ViewModelProvider(this, new PostPaging3ViewModel.Factory(getLifecycle(), mExecutor, mPaging3Retrofit,
accessToken, accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences,
null, null, null, postType, sortType, null, null,
null, null, null)).get(PostPaging3ViewModel.class);
viewModel.getPosts().observe(this, postPagingData -> {
adapter.submitData(getLifecycle(), postPagingData);
});
}
@Override
protected SharedPreferences getDefaultSharedPreferences() {
return mSharedPreferences;
}
@Override
protected CustomThemeWrapper getCustomThemeWrapper() {
return mCustomThemeWrapper;
}
@Override
protected void applyCustomTheme() {
}
}

View File

@ -31,7 +31,7 @@ import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.paging.PagedListAdapter;
import androidx.paging.PagingDataAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
@ -102,7 +102,7 @@ import retrofit2.Retrofit;
* Created by alex on 2/25/18.
*/
public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHolder> implements CacheManager {
public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerView.ViewHolder> implements CacheManager {
private static final int VIEW_TYPE_POST_CARD_VIDEO_AUTOPLAY_TYPE = 1;
private static final int VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE = 2;
private static final int VIEW_TYPE_POST_CARD_TEXT_TYPE = 3;

View File

@ -378,4 +378,97 @@ public interface RedditAPI {
@GET("{sortType}?raw_json=1")
ListenableFuture<Response<String>> getBestPostsListenableFuture(@Path("sortType") String sortType, @Query("t") String sortTime,
@Query("after") String lastItem, @HeaderMap Map<String, String> headers);
@GET("r/{subredditName}/{sortType}.json?raw_json=1&limit=25")
ListenableFuture<Response<String>> getSubredditBestPostsOauthListenableFuture(@Path("subredditName") String subredditName, @Path("sortType") String sortType,
@Query("after") String lastItem, @HeaderMap Map<String, String> headers);
@GET("r/{subredditName}/{sortType}.json?raw_json=1&limit=25")
ListenableFuture<Response<String>> getSubredditBestPostsOauthListenableFuture(@Path("subredditName") String subredditName, @Path("sortType") String sortType,
@Query("t") String sortTime, @Query("after") String lastItem,
@HeaderMap Map<String, String> headers);
@GET("r/{subredditName}/{sortType}.json?raw_json=1&limit=25")
ListenableFuture<Response<String>> getSubredditBestPostsListenableFuture(@Path("subredditName") String subredditName, @Path("sortType") String sortType,
@Query("after") String lastItem);
@GET("r/{subredditName}/{sortType}.json?raw_json=1&limit=25")
ListenableFuture<Response<String>> getSubredditBestPostsListenableFuture(@Path("subredditName") String subredditName, @Path("sortType") String sortType,
@Query("t") String sortTime, @Query("after") String lastItem);
@GET("user/{username}/{where}.json?&type=links&raw_json=1&limit=25")
ListenableFuture<Response<String>> getUserPostsOauthListenableFuture(@Path("username") String username, @Path("where") String where,
@Query("after") String lastItem, @Query("sort") String sortType, @HeaderMap Map<String, String> headers);
@GET("user/{username}/{where}.json?&type=links&raw_json=1&limit=25")
ListenableFuture<Response<String>> getUserPostsOauthListenableFuture(@Path("username") String username, @Path("where") String where,
@Query("after") String lastItem, @Query("sort") String sortType,
@Query("t") String sortTime, @HeaderMap Map<String, String> headers);
@GET("user/{username}/submitted.json?raw_json=1&limit=25")
ListenableFuture<Response<String>> getUserPostsListenableFuture(@Path("username") String username, @Query("after") String lastItem,
@Query("sort") String sortType);
@GET("user/{username}/submitted.json?raw_json=1&limit=25")
ListenableFuture<Response<String>> getUserPostsListenableFuture(@Path("username") String username, @Query("after") String lastItem,
@Query("sort") String sortType, @Query("t") String sortTime);
@GET("search.json?include_over_18=1&raw_json=1&type=link")
ListenableFuture<Response<String>> searchPostsOauthListenableFuture(@Query("q") String query, @Query("after") String after,
@Query("sort") String sort, @Query("source") String source,
@HeaderMap Map<String, String> headers);
@GET("search.json?include_over_18=1&raw_json=1&type=link")
ListenableFuture<Response<String>> searchPostsOauthListenableFuture(@Query("q") String query, @Query("after") String after,
@Query("sort") String sort, @Query("t") String sortTime,
@Query("source") String source,
@HeaderMap Map<String, String> headers);
@GET("search.json?include_over_18=1&raw_json=1&type=link")
ListenableFuture<Response<String>> searchPostsListenableFuture(@Query("q") String query, @Query("after") String after,
@Query("sort") String sort, @Query("source") String source);
@GET("search.json?include_over_18=1&raw_json=1&type=link")
ListenableFuture<Response<String>> searchPostsListenableFuture(@Query("q") String query, @Query("after") String after,
@Query("sort") String sort, @Query("t") String sortTime,
@Query("source") String source);
@GET("r/{subredditName}/search.json?include_over_18=1&raw_json=1&type=link&restrict_sr=true")
ListenableFuture<Response<String>> searchPostsInSpecificSubredditOauthListenableFuture(@Path("subredditName") String subredditName,
@Query("q") String query, @Query("sort") String sort,
@Query("after") String after,
@HeaderMap Map<String, String> headers);
@GET("r/{subredditName}/search.json?include_over_18=1&raw_json=1&type=link&restrict_sr=true")
ListenableFuture<Response<String>> searchPostsInSpecificSubredditOauthListenableFuture(@Path("subredditName") String subredditName,
@Query("q") String query, @Query("sort") String sort,
@Query("t") String sortTime, @Query("after") String after,
@HeaderMap Map<String, String> headers);
@GET("r/{subredditName}/search.json?include_over_18=1&raw_json=1&type=link&restrict_sr=true")
ListenableFuture<Response<String>> searchPostsInSpecificSubredditListenableFuture(@Path("subredditName") String subredditName,
@Query("q") String query, @Query("sort") String sort,
@Query("after") String after);
@GET("r/{subredditName}/search.json?include_over_18=1&raw_json=1&type=link&restrict_sr=true")
ListenableFuture<Response<String>> searchPostsInSpecificSubredditListenableFuture(@Path("subredditName") String subredditName,
@Query("q") String query, @Query("sort") String sort,
@Query("t") String sortTime, @Query("after") String after);
@GET("{multipath}?raw_json=1")
ListenableFuture<Response<String>> getMultiRedditPostsListenableFuture(@Path(value = "multipath", encoded = true) String multiPath,
@Query("after") String after);
@GET("{multipath}?raw_json=1")
ListenableFuture<Response<String>> getMultiRedditPostsListenableFuture(@Path(value = "multipath", encoded = true) String multiPath,
@Query("after") String after, @Query("t") String sortTime);
@GET("{multipath}.json?raw_json=1")
ListenableFuture<Response<String>> getMultiRedditPostsOauthListenableFuture(@Path(value = "multipath", encoded = true) String multiPath,
@Query("after") String after, @Query("t") String sortTime,
@HeaderMap Map<String, String> headers);
@GET("{multipath}.json?raw_json=1")
ListenableFuture<Response<String>> getMultiRedditPostsOauthListenableFuture(@Path(value = "multipath", encoded = true) String multiPath,
@Query("after") String after, @HeaderMap Map<String, String> headers);
}

View File

@ -37,7 +37,6 @@ import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
@ -72,7 +71,6 @@ import ml.docilealligator.infinityforreddit.ActivityToolbarInterface;
import ml.docilealligator.infinityforreddit.FetchPostFilterReadPostsAndConcatenatedSubredditNames;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.NetworkState;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RecyclerViewContentScrollingInterface;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
@ -120,12 +118,11 @@ import ml.docilealligator.infinityforreddit.events.ChangeVideoAutoplayEvent;
import ml.docilealligator.infinityforreddit.events.ChangeVoteButtonsPositionEvent;
import ml.docilealligator.infinityforreddit.events.NeedForPostListFromPostFragmentEvent;
import ml.docilealligator.infinityforreddit.events.PostUpdateEventToPostList;
import ml.docilealligator.infinityforreddit.events.ProvidePostListToViewPostDetailActivityEvent;
import ml.docilealligator.infinityforreddit.events.ShowDividerInCompactLayoutPreferenceEvent;
import ml.docilealligator.infinityforreddit.events.ShowThumbnailOnTheRightInCompactLayoutEvent;
import ml.docilealligator.infinityforreddit.post.NewPostViewModel;
import ml.docilealligator.infinityforreddit.post.Post;
import ml.docilealligator.infinityforreddit.post.PostDataSource;
import ml.docilealligator.infinityforreddit.post.PostViewModel;
import ml.docilealligator.infinityforreddit.postfilter.PostFilter;
import ml.docilealligator.infinityforreddit.postfilter.PostFilterUsage;
import ml.docilealligator.infinityforreddit.readpost.ReadPost;
@ -168,7 +165,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
ImageView mFetchPostInfoImageView;
@BindView(R.id.fetch_post_info_text_view_post_fragment)
TextView mFetchPostInfoTextView;
PostViewModel mPostViewModel;
NewPostViewModel mPostViewModel;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@ -1110,34 +1107,34 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private void initializeAndBindPostViewModel(String accessToken) {
if (postType == PostDataSource.TYPE_SEARCH) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
new Handler(), accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
mPostViewModel = new ViewModelProvider(PostFragment.this, new NewPostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, subredditName, query, trendingSource,
postType, sortType, postFilter, readPosts)).get(PostViewModel.class);
postType, sortType, postFilter, readPosts)).get(NewPostViewModel.class);
} else if (postType == PostDataSource.TYPE_SUBREDDIT) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
new Handler(), accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
mPostViewModel = new ViewModelProvider(PostFragment.this, new NewPostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, subredditName, postType, sortType,
postFilter, readPosts)).get(PostViewModel.class);
postFilter, readPosts)).get(NewPostViewModel.class);
} else if (postType == PostDataSource.TYPE_MULTI_REDDIT) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
new Handler(), accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
mPostViewModel = new ViewModelProvider(PostFragment.this, new NewPostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, multiRedditPath, postType, sortType,
postFilter, readPosts)).get(PostViewModel.class);
postFilter, readPosts)).get(NewPostViewModel.class);
} else if (postType == PostDataSource.TYPE_USER) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
new Handler(), accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
mPostViewModel = new ViewModelProvider(PostFragment.this, new NewPostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, accessToken,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, username, postType, sortType, postFilter,
where, readPosts)).get(PostViewModel.class);
where, readPosts)).get(NewPostViewModel.class);
} else {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
new Handler(), mOauthRetrofit, accessToken,
mPostViewModel = new ViewModelProvider(PostFragment.this, new NewPostViewModel.Factory(mExecutor,
mOauthRetrofit, accessToken,
accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences,
postType, sortType, postFilter, readPosts)).get(PostViewModel.class);
postType, sortType, postFilter, readPosts)).get(NewPostViewModel.class);
}
bindPostViewModel();
@ -1146,43 +1143,43 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private void initializeAndBindPostViewModelForAnonymous(String concatenatedSubredditNames) {
//For anonymous user
if (postType == PostDataSource.TYPE_SEARCH) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
new Handler(), mRetrofit, null,
mPostViewModel = new ViewModelProvider(PostFragment.this, new NewPostViewModel.Factory(mExecutor,
mRetrofit, null,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, subredditName, query, trendingSource,
postType, sortType, postFilter, readPosts)).get(PostViewModel.class);
postType, sortType, postFilter, readPosts)).get(NewPostViewModel.class);
} else if (postType == PostDataSource.TYPE_SUBREDDIT) {
mPostViewModel = new ViewModelProvider(this, new PostViewModel.Factory(mExecutor,
new Handler(), mRetrofit, null,
mPostViewModel = new ViewModelProvider(this, new NewPostViewModel.Factory(mExecutor,
mRetrofit, null,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, subredditName, postType, sortType,
postFilter, readPosts)).get(PostViewModel.class);
postFilter, readPosts)).get(NewPostViewModel.class);
} else if (postType == PostDataSource.TYPE_MULTI_REDDIT) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
new Handler(), mRetrofit, null,
mPostViewModel = new ViewModelProvider(PostFragment.this, new NewPostViewModel.Factory(mExecutor,
mRetrofit, null,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, multiRedditPath, postType, sortType, postFilter,
readPosts)).get(PostViewModel.class);
readPosts)).get(NewPostViewModel.class);
} else if (postType == PostDataSource.TYPE_USER) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
new Handler(), mRetrofit, null,
mPostViewModel = new ViewModelProvider(PostFragment.this, new NewPostViewModel.Factory(mExecutor,
mRetrofit, null,
accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, username, postType, sortType, postFilter,
where, readPosts)).get(PostViewModel.class);
where, readPosts)).get(NewPostViewModel.class);
} else {
//Anonymous Front Page
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
new Handler(), mRetrofit,
mSharedPreferences, concatenatedSubredditNames, postType, sortType, postFilter)).get(PostViewModel.class);
mPostViewModel = new ViewModelProvider(PostFragment.this, new NewPostViewModel.Factory(mExecutor,
mRetrofit,
mSharedPreferences, concatenatedSubredditNames, postType, sortType, postFilter)).get(NewPostViewModel.class);
}
bindPostViewModel();
}
private void bindPostViewModel() {
mPostViewModel.getPosts().observe(getViewLifecycleOwner(), posts -> mAdapter.submitList(posts));
mPostViewModel.getPosts().observe(getViewLifecycleOwner(), posts -> mAdapter.submitData(getViewLifecycleOwner().getLifecycle(), posts));
mPostViewModel.hasPost().observe(getViewLifecycleOwner(), hasPost -> {
/*mPostViewModel.hasPost().observe(getViewLifecycleOwner(), hasPost -> {
this.hasPost = hasPost;
mSwipeRefreshLayout.setRefreshing(false);
if (hasPost) {
@ -1209,7 +1206,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}
});
mPostViewModel.getPaginationNetworkState().observe(getViewLifecycleOwner(), networkState -> mAdapter.setNetworkState(networkState));
mPostViewModel.getPaginationNetworkState().observe(getViewLifecycleOwner(), networkState -> mAdapter.setNetworkState(networkState));*/
}
public void changeSortType(SortType sortType) {
@ -1606,7 +1603,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Subscribe
public void onPostUpdateEvent(PostUpdateEventToPostList event) {
PagedList<Post> posts = mAdapter.getCurrentList();
//TODO: fix this
/*PagedList<Post> posts = mAdapter.getCurrentList();
if (posts != null && event.positionInList >= 0 && event.positionInList < posts.size()) {
Post post = posts.get(event.positionInList);
if (post != null && post.getFullName().equals(event.post.getFullName())) {
@ -1620,7 +1618,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
post.setSaved(event.post.isSaved());
mAdapter.notifyItemChanged(event.positionInList);
}
}
}*/
}
@Subscribe
@ -1887,9 +1885,10 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Subscribe
public void onNeedForPostListFromPostRecyclerViewAdapterEvent(NeedForPostListFromPostFragmentEvent event) {
if (postFragmentId == event.postFragmentTimeId) {
//TODO: fix this
/*if (postFragmentId == event.postFragmentTimeId) {
EventBus.getDefault().post(new ProvidePostListToViewPostDetailActivityEvent(postFragmentId, new ArrayList<>(mPostViewModel.getPosts().getValue())));
}
}*/
}
@Subscribe

View File

@ -0,0 +1,281 @@
package ml.docilealligator.infinityforreddit.post;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelKt;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.Pager;
import androidx.paging.PagingConfig;
import androidx.paging.PagingData;
import androidx.paging.PagingLiveData;
import java.util.List;
import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.SortType;
import ml.docilealligator.infinityforreddit.postfilter.PostFilter;
import ml.docilealligator.infinityforreddit.readpost.ReadPost;
import retrofit2.Retrofit;
public class NewPostViewModel extends ViewModel {
private PostPaging3Repository repository;
private LiveData<PagingData<Post>> posts;
private PostPaging3PagingSource paging3PagingSource;
private MutableLiveData<SortType> sortTypeLiveData;
private MutableLiveData<PostFilter> postFilterLiveData;
private SortTypeAndPostFilterLiveData sortTypeAndPostFilterLiveData;
public NewPostViewModel(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences cache, int postType,
SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
sortTypeLiveData = new MutableLiveData<>();
sortTypeLiveData.postValue(sortType);
postFilterLiveData = new MutableLiveData<>();
postFilterLiveData.postValue(postFilter);
sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData);
repository = new PostPaging3Repository(executor, retrofit, accessToken, accountName,
sharedPreferences, cache, postType, sortType, postFilter, readPostList);
paging3PagingSource = repository.returnPagingSoruce();
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> {
paging3PagingSource.changeSortTypeAndPostFilter(
sortTypeLiveData.getValue(), postFilterLiveData.getValue());
return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), ViewModelKt.getViewModelScope(this));
});
}
public NewPostViewModel(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences cache, String subredditName,
int postType, SortType sortType, PostFilter postFilter,
List<ReadPost> readPostList) {
sortTypeLiveData = new MutableLiveData<>();
sortTypeLiveData.postValue(sortType);
postFilterLiveData = new MutableLiveData<>();
postFilterLiveData.postValue(postFilter);
sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData);
repository = new PostPaging3Repository(executor, retrofit, accessToken, accountName,
sharedPreferences, cache, subredditName, postType, sortType, postFilter, readPostList);
paging3PagingSource = repository.returnPagingSoruce();
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> {
paging3PagingSource.changeSortTypeAndPostFilter(
sortTypeLiveData.getValue(), postFilterLiveData.getValue());
return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), ViewModelKt.getViewModelScope(this));
});
}
public NewPostViewModel(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences cache, String username,
int postType, SortType sortType, PostFilter postFilter, String where,
List<ReadPost> readPostList) {
sortTypeLiveData = new MutableLiveData<>();
sortTypeLiveData.postValue(sortType);
postFilterLiveData = new MutableLiveData<>();
postFilterLiveData.postValue(postFilter);
sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData);
repository = new PostPaging3Repository(executor, retrofit, accessToken, accountName,
sharedPreferences, cache, username, postType, sortType, postFilter, where, readPostList);
paging3PagingSource = repository.returnPagingSoruce();
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> {
paging3PagingSource.changeSortTypeAndPostFilter(
sortTypeLiveData.getValue(), postFilterLiveData.getValue());
return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), ViewModelKt.getViewModelScope(this));
});
}
public NewPostViewModel(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences cache, String subredditName,
String query, String trendingSource, int postType, SortType sortType,
PostFilter postFilter, List<ReadPost> readPostList) {
sortTypeLiveData = new MutableLiveData<>();
sortTypeLiveData.postValue(sortType);
postFilterLiveData = new MutableLiveData<>();
postFilterLiveData.postValue(postFilter);
sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData);
repository = new PostPaging3Repository(executor, retrofit, accessToken, accountName,
sharedPreferences, cache, subredditName, query, trendingSource, postType, sortType, postFilter,
readPostList);
paging3PagingSource = repository.returnPagingSoruce();
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> {
paging3PagingSource.changeSortTypeAndPostFilter(
sortTypeLiveData.getValue(), postFilterLiveData.getValue());
return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), ViewModelKt.getViewModelScope(this));
});
}
public LiveData<PagingData<Post>> getPosts() {
return posts;
}
private PostPaging3PagingSource returnPagingSoruce() {
return repository.returnPagingSoruce();
}
public void changeSortType(SortType sortType) {
sortTypeLiveData.postValue(sortType);
}
public void changePostFilter(PostFilter postFilter) {
postFilterLiveData.postValue(postFilter);
}
public void refresh() {
}
public void retryLoadingMore() {
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private Executor executor;
private Retrofit retrofit;
private String accessToken;
private String accountName;
private SharedPreferences sharedPreferences;
private SharedPreferences postFeedScrolledPositionSharedPreferences;
private String name;
private String query;
private String trendingSource;
private int postType;
private SortType sortType;
private PostFilter postFilter;
private String userWhere;
private List<ReadPost> readPostList;
public Factory(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
int postType, SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
this.executor = executor;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.postType = postType;
this.sortType = sortType;
this.postFilter = postFilter;
this.readPostList = readPostList;
}
public Factory(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String name, int postType, SortType sortType, PostFilter postFilter,
List<ReadPost> readPostList) {this.executor = executor;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.name = name;
this.postType = postType;
this.sortType = sortType;
this.postFilter = postFilter;
this.readPostList = readPostList;
}
//User posts
public Factory(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String username, int postType, SortType sortType, PostFilter postFilter, String where,
List<ReadPost> readPostList) {
this.executor = executor;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.name = username;
this.postType = postType;
this.sortType = sortType;
this.postFilter = postFilter;
userWhere = where;
this.readPostList = readPostList;
}
public Factory(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String name, String query, String trendingSource, int postType, SortType sortType,
PostFilter postFilter, List<ReadPost> readPostList) {
this.executor = executor;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.name = name;
this.query = query;
this.trendingSource = trendingSource;
this.postType = postType;
this.sortType = sortType;
this.postFilter = postFilter;
this.readPostList = readPostList;
}
//Anonymous Front Page
public Factory(Executor executor, Retrofit retrofit, SharedPreferences sharedPreferences,
String concatenatedSubredditNames, int postType, SortType sortType, PostFilter postFilter) {
this.executor = executor;
this.retrofit = retrofit;
this.sharedPreferences = sharedPreferences;
this.name = concatenatedSubredditNames;
this.postType = postType;
this.sortType = sortType;
this.postFilter = postFilter;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if (postType == PostDataSource.TYPE_FRONT_PAGE) {
return (T) new NewPostViewModel(executor, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, postType, sortType, postFilter, readPostList);
} else if (postType == PostDataSource.TYPE_SEARCH) {
return (T) new NewPostViewModel(executor, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, name, query, trendingSource, postType, sortType,
postFilter, readPostList);
} else if (postType == PostDataSource.TYPE_SUBREDDIT || postType == PostDataSource.TYPE_MULTI_REDDIT) {
return (T) new NewPostViewModel(executor, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, name, postType, sortType,
postFilter, readPostList);
} else if (postType == PostDataSource.TYPE_ANONYMOUS_FRONT_PAGE) {
return (T) new NewPostViewModel(executor, retrofit, null, null, sharedPreferences,
null, name, postType, sortType,
postFilter, null);
} else {
return (T) new NewPostViewModel(executor, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, name, postType, sortType,
postFilter, userWhere, readPostList);
}
}
}
private static class SortTypeAndPostFilterLiveData extends MediatorLiveData<Pair<PostFilter, SortType>> {
public SortTypeAndPostFilterLiveData(LiveData<SortType> sortTypeLiveData, LiveData<PostFilter> postFilterLiveData) {
addSource(sortTypeLiveData, sortType -> setValue(Pair.create(postFilterLiveData.getValue(), sortType)));
addSource(postFilterLiveData, postFilter -> setValue(Pair.create(postFilter, sortTypeLiveData.getValue())));
}
}
}

View File

@ -4,7 +4,6 @@ import android.content.SharedPreferences;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.paging.ListenableFuturePagingSource;
import androidx.paging.PagingState;
@ -19,17 +18,31 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.NetworkState;
import ml.docilealligator.infinityforreddit.SortType;
import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.postfilter.PostFilter;
import ml.docilealligator.infinityforreddit.readpost.ReadPost;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
import ml.docilealligator.infinityforreddit.utils.SharedPreferencesUtils;
import retrofit2.HttpException;
import retrofit2.Response;
import retrofit2.Retrofit;
public class PostPaging3PagingSource extends ListenableFuturePagingSource<String, Post> {
public static final int TYPE_FRONT_PAGE = 0;
public static final int TYPE_SUBREDDIT = 1;
public static final int TYPE_USER = 2;
public static final int TYPE_SEARCH = 3;
public static final int TYPE_MULTI_REDDIT = 4;
public static final int TYPE_ANONYMOUS_FRONT_PAGE = 5;
public static final String USER_WHERE_SUBMITTED = "submitted";
public static final String USER_WHERE_UPVOTED = "upvoted";
public static final String USER_WHERE_DOWNVOTED = "downvoted";
public static final String USER_WHERE_HIDDEN = "hidden";
public static final String USER_WHERE_SAVED = "saved";
public static final String USER_WHERE_GILDED = "gilded";
private Executor executor;
private Retrofit retrofit;
private String accessToken;
@ -47,10 +60,6 @@ public class PostPaging3PagingSource extends ListenableFuturePagingSource<String
private String multiRedditPath;
private LinkedHashSet<Post> postLinkedHashSet;
private MutableLiveData<NetworkState> paginationNetworkStateLiveData;
private MutableLiveData<NetworkState> initialLoadStateLiveData;
private MutableLiveData<Boolean> hasPostLiveData;
PostPaging3PagingSource(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences,
SharedPreferences postFeedScrolledPositionSharedPreferences, int postType,
@ -61,9 +70,6 @@ public class PostPaging3PagingSource extends ListenableFuturePagingSource<String
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
paginationNetworkStateLiveData = new MutableLiveData<>();
initialLoadStateLiveData = new MutableLiveData<>();
hasPostLiveData = new MutableLiveData<>();
this.postType = postType;
this.sortType = sortType == null ? new SortType(SortType.Type.BEST) : sortType;
this.postFilter = postFilter;
@ -71,6 +77,83 @@ public class PostPaging3PagingSource extends ListenableFuturePagingSource<String
postLinkedHashSet = new LinkedHashSet<>();
}
PostPaging3PagingSource(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String path, int postType, SortType sortType, PostFilter postFilter,
List<ReadPost> readPostList) {
this.executor = executor;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
if (postType == TYPE_SUBREDDIT || postType == TYPE_ANONYMOUS_FRONT_PAGE) {
this.subredditOrUserName = path;
} else {
if (sortType != null) {
if (path.endsWith("/")) {
multiRedditPath = path + sortType.getType().value;
} else {
multiRedditPath = path + "/" + sortType.getType().value;
}
} else {
multiRedditPath = path;
}
}
this.postType = postType;
if (sortType == null) {
if (path.equals("popular") || path.equals("all")) {
this.sortType = new SortType(SortType.Type.HOT);
} else {
this.sortType = new SortType(SortType.Type.BEST);
}
} else {
this.sortType = sortType;
}
this.postFilter = postFilter;
this.readPostList = readPostList;
postLinkedHashSet = new LinkedHashSet<>();
}
PostPaging3PagingSource(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String subredditOrUserName, int postType, SortType sortType, PostFilter postFilter,
String where, List<ReadPost> readPostList) {
this.executor = executor;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.subredditOrUserName = subredditOrUserName;
this.postType = postType;
this.sortType = sortType == null ? new SortType(SortType.Type.NEW) : sortType;
this.postFilter = postFilter;
userWhere = where;
this.readPostList = readPostList;
postLinkedHashSet = new LinkedHashSet<>();
}
PostPaging3PagingSource(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String subredditOrUserName, String query, String trendingSource, int postType,
SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
this.executor = executor;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.subredditOrUserName = subredditOrUserName;
this.query = query;
this.trendingSource = trendingSource;
this.postType = postType;
this.sortType = sortType == null ? new SortType(SortType.Type.RELEVANCE) : sortType;
this.postFilter = postFilter;
postLinkedHashSet = new LinkedHashSet<>();
this.readPostList = readPostList;
}
@Nullable
@Override
public String getRefreshKey(@NonNull PagingState<String, Post> pagingState) {
@ -80,24 +163,21 @@ public class PostPaging3PagingSource extends ListenableFuturePagingSource<String
@NonNull
@Override
public ListenableFuture<LoadResult<String, Post>> loadFuture(@NonNull LoadParams<String> loadParams) {
Log.i("asfsaf", "s" + loadParams.getKey());
RedditAPI api = retrofit.create(RedditAPI.class);
ListenableFuture<Response<String>> bestPost;
if(sortType.getTime() != null) {
bestPost = api.getBestPostsListenableFuture(sortType.getType().value, sortType.getTime().value, loadParams.getKey(),
APIUtils.getOAuthHeader(accessToken));
} else {
bestPost = api.getBestPostsListenableFuture(sortType.getType().value, loadParams.getKey(), APIUtils.getOAuthHeader(accessToken));
switch (postType) {
case TYPE_FRONT_PAGE:
return loadHomePosts(loadParams, api);
case TYPE_SUBREDDIT:
return loadSubredditPosts(loadParams, api);
case TYPE_USER:
return loadUserPosts(loadParams, api);
case TYPE_SEARCH:
return loadSearchPosts(loadParams, api);
case TYPE_MULTI_REDDIT:
return loadMultiRedditPosts(loadParams, api);
default:
return loadAnonymousHomePosts(loadParams, api);
}
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(bestPost, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
public LoadResult<String, Post> transformData(Response<String> response) {
@ -106,7 +186,7 @@ public class PostPaging3PagingSource extends ListenableFuturePagingSource<String
LinkedHashSet<Post> newPosts = ParsePost.parsePostsSync(responseString, -1, postFilter, readPostList);
String lastItem = ParsePost.getLastItem(responseString);
if (newPosts == null) {
return new LoadResult.Error<>(new Exception("Error parsing more posts"));
return new LoadResult.Error<>(new Exception("Error parsing posts"));
} else {
int currentPostsSize = postLinkedHashSet.size();
postLinkedHashSet.addAll(newPosts);
@ -120,4 +200,195 @@ public class PostPaging3PagingSource extends ListenableFuturePagingSource<String
return new LoadResult.Error<>(new Exception("Response failed"));
}
}
private ListenableFuture<LoadResult<String, Post>> loadHomePosts(@NonNull LoadParams<String> loadParams, RedditAPI api) {
ListenableFuture<Response<String>> bestPost;
String afterKey;
if (loadParams.getKey() == null) {
boolean savePostFeedScrolledPosition = sortType != null && sortType.getType() == SortType.Type.BEST && sharedPreferences.getBoolean(SharedPreferencesUtils.SAVE_FRONT_PAGE_SCROLLED_POSITION, false);
if (savePostFeedScrolledPosition) {
String accountNameForCache = accountName == null ? SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_ANONYMOUS : accountName;
afterKey = postFeedScrolledPositionSharedPreferences.getString(accountNameForCache + SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_FRONT_PAGE_BASE, null);
} else {
afterKey = null;
}
} else {
afterKey = loadParams.getKey();
}
if(sortType.getTime() != null) {
bestPost = api.getBestPostsListenableFuture(sortType.getType().value, sortType.getTime().value, afterKey,
APIUtils.getOAuthHeader(accessToken));
} else {
bestPost = api.getBestPostsListenableFuture(sortType.getType().value, afterKey, APIUtils.getOAuthHeader(accessToken));
}
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(bestPost, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
private ListenableFuture<LoadResult<String, Post>> loadSubredditPosts(@NonNull LoadParams<String> loadParams, RedditAPI api) {
ListenableFuture<Response<String>> subredditPost;
if (accessToken == null) {
if (sortType.getTime() != null) {
subredditPost = api.getSubredditBestPostsListenableFuture(subredditOrUserName, sortType.getType().value, sortType.getTime().value, loadParams.getKey());
} else {
subredditPost = api.getSubredditBestPostsListenableFuture(subredditOrUserName, sortType.getType().value, loadParams.getKey());
}
} else {
if (sortType.getTime() != null) {
subredditPost = api.getSubredditBestPostsOauthListenableFuture(subredditOrUserName, sortType.getType().value,
sortType.getTime().value, loadParams.getKey(), APIUtils.getOAuthHeader(accessToken));
} else {
subredditPost = api.getSubredditBestPostsOauthListenableFuture(subredditOrUserName, sortType.getType().value,
loadParams.getKey(), APIUtils.getOAuthHeader(accessToken));
}
}
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(subredditPost, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
private ListenableFuture<LoadResult<String, Post>> loadUserPosts(@NonNull LoadParams<String> loadParams, RedditAPI api) {
ListenableFuture<Response<String>> userPosts;
if (accessToken == null) {
if (sortType.getTime() != null) {
userPosts = api.getUserPostsListenableFuture(subredditOrUserName, loadParams.getKey(), sortType.getType().value,
sortType.getTime().value);
} else {
userPosts = api.getUserPostsListenableFuture(subredditOrUserName, loadParams.getKey(), sortType.getType().value);
}
} else {
if (sortType.getTime() != null) {
userPosts = api.getUserPostsOauthListenableFuture(subredditOrUserName, userWhere, loadParams.getKey(), sortType.getType().value,
sortType.getTime().value, APIUtils.getOAuthHeader(accessToken));
} else {
userPosts = api.getUserPostsOauthListenableFuture(subredditOrUserName, userWhere, loadParams.getKey(), sortType.getType().value,
APIUtils.getOAuthHeader(accessToken));
}
}
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(userPosts, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
private ListenableFuture<LoadResult<String, Post>> loadSearchPosts(@NonNull LoadParams<String> loadParams, RedditAPI api) {
ListenableFuture<Response<String>> searchPosts;
if (subredditOrUserName == null) {
if (accessToken == null) {
if (sortType.getTime() != null) {
searchPosts = api.searchPostsListenableFuture(query, loadParams.getKey(), sortType.getType().value, sortType.getTime().value,
trendingSource);
} else {
searchPosts = api.searchPostsListenableFuture(query, loadParams.getKey(), sortType.getType().value, trendingSource);
}
} else {
if(sortType.getTime() != null) {
searchPosts = api.searchPostsOauthListenableFuture(query, loadParams.getKey(), sortType.getType().value,
sortType.getTime().value, trendingSource, APIUtils.getOAuthHeader(accessToken));
} else {
searchPosts = api.searchPostsOauthListenableFuture(query, loadParams.getKey(), sortType.getType().value, trendingSource,
APIUtils.getOAuthHeader(accessToken));
}
}
} else {
if (accessToken == null) {
if (sortType.getTime() != null) {
searchPosts = api.searchPostsInSpecificSubredditListenableFuture(subredditOrUserName, query,
sortType.getType().value, sortType.getTime().value, loadParams.getKey());
} else {
searchPosts = api.searchPostsInSpecificSubredditListenableFuture(subredditOrUserName, query,
sortType.getType().value, loadParams.getKey());
}
} else {
if (sortType.getTime() != null) {
searchPosts = api.searchPostsInSpecificSubredditOauthListenableFuture(subredditOrUserName, query,
sortType.getType().value, sortType.getTime().value, loadParams.getKey(),
APIUtils.getOAuthHeader(accessToken));
} else {
searchPosts = api.searchPostsInSpecificSubredditOauthListenableFuture(subredditOrUserName, query,
sortType.getType().value, loadParams.getKey(),
APIUtils.getOAuthHeader(accessToken));
}
}
}
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(searchPosts, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
private ListenableFuture<LoadResult<String, Post>> loadMultiRedditPosts(@NonNull LoadParams<String> loadParams, RedditAPI api) {
ListenableFuture<Response<String>> multiRedditPosts;
if (accessToken == null) {
if (sortType.getTime() != null) {
multiRedditPosts = api.getMultiRedditPostsListenableFuture(multiRedditPath, loadParams.getKey(), sortType.getTime().value);
} else {
multiRedditPosts = api.getMultiRedditPostsListenableFuture(multiRedditPath, loadParams.getKey());
}
} else {
if (sortType.getTime() != null) {
multiRedditPosts = api.getMultiRedditPostsOauthListenableFuture(multiRedditPath, loadParams.getKey(),
sortType.getTime().value, APIUtils.getOAuthHeader(accessToken));
} else {
multiRedditPosts = api.getMultiRedditPostsOauthListenableFuture(multiRedditPath, loadParams.getKey(),
APIUtils.getOAuthHeader(accessToken));
}
}
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(multiRedditPosts, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
private ListenableFuture<LoadResult<String, Post>> loadAnonymousHomePosts(@NonNull LoadParams<String> loadParams, RedditAPI api) {
ListenableFuture<Response<String>> anonymousHomePosts;
if (sortType.getTime() != null) {
anonymousHomePosts = api.getSubredditBestPostsListenableFuture(subredditOrUserName, sortType.getType().value, sortType.getTime().value, loadParams.getKey());
} else {
anonymousHomePosts = api.getSubredditBestPostsListenableFuture(subredditOrUserName, sortType.getType().value, loadParams.getKey());
}
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(anonymousHomePosts, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor);
}
void changeSortTypeAndPostFilter(SortType sortType, PostFilter postFilter) {
Log.i("asdasfd", "s6 " + (postFilter == null));
this.sortType = sortType;
this.postFilter = postFilter;
}
}

View File

@ -2,13 +2,6 @@ package ml.docilealligator.infinityforreddit.post;
import android.content.SharedPreferences;
import androidx.lifecycle.LiveData;
import androidx.paging.Pager;
import androidx.paging.PagingConfig;
import androidx.paging.PagingData;
import androidx.paging.PagingLiveData;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.concurrent.Executor;
@ -18,53 +11,43 @@ import ml.docilealligator.infinityforreddit.readpost.ReadPost;
import retrofit2.Retrofit;
public class PostPaging3Repository {
private Executor executor;
private Retrofit retrofit;
private String accessToken;
private String accountName;
private SharedPreferences sharedPreferences;
private SharedPreferences postFeedScrolledPositionSharedPreferences;
private String subredditOrUserName;
private String query;
private String trendingSource;
private int postType;
private SortType sortType;
private PostFilter postFilter;
private List<ReadPost> readPostList;
private String userWhere;
private String multiRedditPath;
private LinkedHashSet<Post> postLinkedHashSet;
private PostPaging3PagingSource paging3PagingSource;
public PostPaging3Repository(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences,
SharedPreferences postFeedScrolledPositionSharedPreferences,
String subredditOrUserName, String query, String trendingSource, int postType,
SortType sortType, PostFilter postFilter, List<ReadPost> readPostList,
String userWhere, String multiRedditPath, LinkedHashSet<Post> postLinkedHashSet) {
this.executor = executor;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.subredditOrUserName = subredditOrUserName;
this.query = query;
this.trendingSource = trendingSource;
this.postType = postType;
this.sortType = sortType;
this.postFilter = postFilter;
this.readPostList = readPostList;
this.userWhere = userWhere;
this.multiRedditPath = multiRedditPath;
this.postLinkedHashSet = postLinkedHashSet;
paging3PagingSource = new PostPaging3PagingSource(executor, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, postType, sortType, postFilter, readPostList);
PostPaging3Repository(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences,
SharedPreferences postFeedScrolledPositionSharedPreferences, int postType,
SortType sortType, PostFilter postFilter, List<ReadPost> readPostList) {
paging3PagingSource = new PostPaging3PagingSource(executor, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, postType, sortType,
postFilter, readPostList);
}
public LiveData<PagingData<Post>> getPostsLiveData() {
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
return PagingLiveData.getLiveData(pager);
PostPaging3Repository(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String name, int postType, SortType sortType, PostFilter postFilter,
List<ReadPost> readPostList) {
paging3PagingSource = new PostPaging3PagingSource(executor, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, name, postType,
sortType, postFilter, readPostList);
}
PostPaging3Repository(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String name, int postType, SortType sortType, PostFilter postFilter,
String userWhere, List<ReadPost> readPostList) {
paging3PagingSource = new PostPaging3PagingSource(executor, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, name, postType,
sortType, postFilter, userWhere, readPostList);
}
PostPaging3Repository(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
String name, String query, String trendingSource, int postType, SortType sortType,
PostFilter postFilter, List<ReadPost> readPostList) {
paging3PagingSource = new PostPaging3PagingSource(executor, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, name, query, trendingSource,
postType, sortType, postFilter, readPostList);
}
public PostPaging3PagingSource returnPagingSoruce() {

View File

@ -1,107 +0,0 @@
package ml.docilealligator.infinityforreddit.post;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelKt;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.Pager;
import androidx.paging.PagingConfig;
import androidx.paging.PagingData;
import androidx.paging.PagingLiveData;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.concurrent.Executor;
import ml.docilealligator.infinityforreddit.SortType;
import ml.docilealligator.infinityforreddit.postfilter.PostFilter;
import ml.docilealligator.infinityforreddit.readpost.ReadPost;
import retrofit2.Retrofit;
public class PostPaging3ViewModel extends ViewModel {
private PostPaging3Repository repository;
private LiveData<PagingData<Post>> posts;
private PostPaging3PagingSource paging3PagingSource;
private Lifecycle lifecycle;
public PostPaging3ViewModel(Lifecycle lifecycle, Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences,
SharedPreferences postFeedScrolledPositionSharedPreferences,
String subredditOrUserName, String query, String trendingSource, int postType,
SortType sortType, PostFilter postFilter, List<ReadPost> readPostList,
String userWhere, String multiRedditPath, LinkedHashSet<Post> postLinkedHashSet) {
repository = new PostPaging3Repository(executor, retrofit, accessToken, accountName, sharedPreferences, postFeedScrolledPositionSharedPreferences,
subredditOrUserName, query, trendingSource, postType, sortType, postFilter, readPostList, userWhere, multiRedditPath, postLinkedHashSet);
paging3PagingSource = repository.returnPagingSoruce();
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), ViewModelKt.getViewModelScope(this));
}
public LiveData<PagingData<Post>> getPosts() {
/*Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), ViewModelKt.getViewModelScope(this));
posts = PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), lifecycle);*/
return posts;
}
private PostPaging3PagingSource returnPagingSoruce() {
return paging3PagingSource;
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private Lifecycle lifecycle;
private Executor executor;
private Retrofit retrofit;
private String accessToken;
private String accountName;
private SharedPreferences sharedPreferences;
private SharedPreferences postFeedScrolledPositionSharedPreferences;
private String subredditOrUserName;
private String query;
private String trendingSource;
private int postType;
private SortType sortType;
private PostFilter postFilter;
private List<ReadPost> readPostList;
private String userWhere;
private String multiRedditPath;
private LinkedHashSet<Post> postLinkedHashSet;
public Factory(Lifecycle lifecycle, Executor executor, Retrofit retrofit, String accessToken, String accountName, SharedPreferences sharedPreferences,
SharedPreferences postFeedScrolledPositionSharedPreferences, String subredditOrUserName,
String query, String trendingSource, int postType, SortType sortType, PostFilter postFilter,
List<ReadPost> readPostList, String userWhere, String multiRedditPath,
LinkedHashSet<Post> postLinkedHashSet) {
this.lifecycle = lifecycle;
this.executor = executor;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.subredditOrUserName = subredditOrUserName;
this.query = query;
this.trendingSource = trendingSource;
this.postType = postType;
this.sortType = sortType;
this.postFilter = postFilter;
this.readPostList = readPostList;
this.userWhere = userWhere;
this.multiRedditPath = multiRedditPath;
this.postLinkedHashSet = postLinkedHashSet;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new PostPaging3ViewModel(lifecycle, executor, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, subredditOrUserName, query, trendingSource,
postType, sortType, postFilter, readPostList, userWhere, multiRedditPath, postLinkedHashSet);
}
}
}

View File

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.Paging3TestActivity"
android:id="@+id/recycler_view"
app:layoutManager=".customviews.LinearLayoutManagerBugFixed" />