emitter) {
97 | synchronized (mEmitterLock) {
98 | mEmitter = emitter;
99 | }
100 | mContentResolver.registerContentObserver(
101 | mQuery.contentUri, true, mContentObserver);
102 | reload();
103 | }
104 |
105 | void release() {
106 | mContentResolver.unregisterContentObserver(mContentObserver);
107 | synchronized (mEmitterLock) {
108 | mEmitter = null;
109 | }
110 | }
111 |
112 | /**
113 | * Loads new {@link Cursor}.
114 | *
115 | * This must be called from {@link #subscribe(FlowableEmitter)} thread
116 | */
117 | synchronized void reload() {
118 | if (isDebugLoggingEnabled()) {
119 | Log.d(TAG, mQuery.toString());
120 | }
121 |
122 | final Cursor c = mContentResolver.query(
123 | mQuery.contentUri,
124 | mQuery.projection,
125 | mQuery.selection,
126 | mQuery.selectionArgs,
127 | mQuery.sortOrder);
128 |
129 | synchronized (mEmitterLock) {
130 | if (mEmitter != null && !mEmitter.isCancelled()) {
131 | if (c != null) {
132 | mEmitter.onNext(c);
133 | } else {
134 | mEmitter.onError(new QueryReturnedNullException());
135 | }
136 | }
137 | }
138 | }
139 |
140 | private final ContentObserver mContentObserver = new ContentObserver(mHandler) {
141 |
142 | @Override
143 | public void onChange(final boolean selfChange) {
144 | mScheduler.scheduleDirect(mReloadRunnable);
145 | }
146 | };
147 |
148 | final Runnable mReloadRunnable = new Runnable() {
149 | @Override
150 | public void run() {
151 | reload();
152 | }
153 | };
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/library/src/test/java/com/doctoror/rxcursorloader/RxCursorLoaderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Yaroslav Mytkalyk
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.doctoror.rxcursorloader;
17 |
18 | import android.content.ContentResolver;
19 | import android.database.Cursor;
20 | import android.net.Uri;
21 | import android.os.Parcel;
22 | import android.provider.MediaStore;
23 |
24 | import org.junit.Before;
25 | import org.junit.Test;
26 | import org.junit.runner.RunWith;
27 | import org.robolectric.RobolectricTestRunner;
28 | import org.robolectric.annotation.Config;
29 |
30 | import androidx.annotation.NonNull;
31 | import androidx.annotation.Nullable;
32 | import io.reactivex.BackpressureStrategy;
33 | import io.reactivex.observers.BaseTestConsumer;
34 | import io.reactivex.observers.TestObserver;
35 | import io.reactivex.schedulers.Schedulers;
36 | import io.reactivex.subscribers.TestSubscriber;
37 |
38 | import static org.junit.Assert.assertEquals;
39 | import static org.junit.Assert.assertNotNull;
40 | import static org.mockito.ArgumentMatchers.any;
41 | import static org.mockito.ArgumentMatchers.eq;
42 | import static org.mockito.Mockito.mock;
43 | import static org.mockito.Mockito.never;
44 | import static org.mockito.Mockito.verify;
45 | import static org.mockito.Mockito.when;
46 |
47 | @Config(manifest = Config.NONE)
48 | @RunWith(RobolectricTestRunner.class)
49 | public final class RxCursorLoaderTest {
50 |
51 | private static final Uri URI = new Uri.Builder().scheme("content")
52 | .authority("com.doctoror.rxcursorloader.test.provider").build();
53 |
54 | private final ContentResolver contentResolver = mock(ContentResolver.class);
55 |
56 | @Before
57 | public void setup() {
58 | final Cursor stubCursor = mock(Cursor.class);
59 | when(contentResolver
60 | .query(eq(URI), (String[]) any(), (String) any(), (String[]) any(), (String) any()))
61 | .thenReturn(stubCursor);
62 | }
63 |
64 | private void assertHasValidOpenCursor(@NonNull final BaseTestConsumer observer) {
65 | observer.assertValueCount(1);
66 | assertValidOpenCursor((Cursor) observer.values().get(0));
67 | }
68 |
69 | private void assertValidOpenCursor(@Nullable final Cursor c) {
70 | assertNotNull(c);
71 | verify(c, never()).close();
72 | }
73 |
74 | private void givenQueryReturnsNull() {
75 | when(contentResolver
76 | .query(eq(URI), (String[]) any(), (String) any(), (String[]) any(), (String) any()))
77 | .thenReturn(null);
78 | }
79 |
80 | @NonNull
81 | private RxCursorLoader.Query buildQuery() {
82 | return new RxCursorLoader.Query.Builder()
83 | .setContentUri(URI).create();
84 | }
85 |
86 | @Test(expected = IllegalStateException.class)
87 | public void noUriThrowsIllegalStateException() {
88 | //noinspection ConstantConditions
89 | RxCursorLoader.flowable(
90 | contentResolver,
91 | new RxCursorLoader.Query.Builder().create(),
92 | Schedulers.trampoline(),
93 | BackpressureStrategy.ERROR);
94 | }
95 |
96 | @Test(expected = NullPointerException.class)
97 | public void nullContentResolverThrowsNullPointerException() {
98 | //noinspection ConstantConditions
99 | RxCursorLoader.flowable(
100 | null, buildQuery(), Schedulers.trampoline(), BackpressureStrategy.ERROR);
101 | }
102 |
103 | @Test(expected = NullPointerException.class)
104 | public void nullQueryThrowsNullPointerException() {
105 | //noinspection ConstantConditions
106 | RxCursorLoader.flowable(
107 | contentResolver, null, Schedulers.trampoline(), BackpressureStrategy.ERROR);
108 | }
109 |
110 | @Test
111 | public void queryIsValidParcelable() {
112 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder()
113 | .setContentUri(URI)
114 | .setProjection(new String[]{MediaStore.Audio.Media._ID})
115 | .setSortOrder(MediaStore.Audio.Artists.ARTIST)
116 | .setSelection(MediaStore.Audio.Artists.ARTIST + "=?")
117 | .setSelectionArgs(new String[]{"Oh Long Johnson"})
118 | .create();
119 |
120 | final Parcel parcel = Parcel.obtain();
121 | query.writeToParcel(parcel, 0);
122 |
123 | parcel.setDataPosition(0);
124 |
125 | final RxCursorLoader.Query fromParcel = RxCursorLoader.Query.CREATOR
126 | .createFromParcel(parcel);
127 | assertEquals(query, fromParcel);
128 | }
129 |
130 | @Test
131 | public void flowableReturnsCursorFromContentProvider() {
132 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder()
133 | .setContentUri(URI)
134 | .create();
135 |
136 | final TestSubscriber observer = RxCursorLoader.flowable(
137 | contentResolver,
138 | query,
139 | Schedulers.trampoline(),
140 | BackpressureStrategy.ERROR).test();
141 |
142 | observer.assertNoErrors();
143 | observer.assertNotComplete();
144 | assertHasValidOpenCursor(observer);
145 |
146 | observer.dispose();
147 | }
148 |
149 | @Test
150 | public void flowableErrorWhenProviderReturnsNull() {
151 | givenQueryReturnsNull();
152 |
153 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder()
154 | .setContentUri(URI)
155 | .create();
156 |
157 | final TestSubscriber observer = RxCursorLoader.flowable(
158 | contentResolver,
159 | query,
160 | Schedulers.trampoline(),
161 | BackpressureStrategy.ERROR).test();
162 |
163 | observer.assertError(QueryReturnedNullException.class);
164 |
165 | observer.dispose();
166 | }
167 |
168 | @Test
169 | public void singleReturnsCursorFromContentProvider() {
170 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder()
171 | .setContentUri(URI)
172 | .create();
173 |
174 | final TestObserver observer = RxCursorLoader.single(contentResolver, query).test();
175 | observer.assertNoErrors();
176 | observer.assertComplete();
177 | assertHasValidOpenCursor(observer);
178 |
179 | observer.dispose();
180 | }
181 |
182 | @Test
183 | public void singleErrorWhenProviderReturnsNull() {
184 | givenQueryReturnsNull();
185 |
186 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder()
187 | .setContentUri(URI)
188 | .create();
189 |
190 | final TestObserver observer = RxCursorLoader.single(contentResolver, query).test();
191 | observer.assertError(QueryReturnedNullException.class);
192 |
193 | observer.dispose();
194 | }
195 | }
196 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2016 Yaroslav Mytkalyk
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/library/src/main/java/com/doctoror/rxcursorloader/RxCursorLoader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Yaroslav Mytkalyk
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.doctoror.rxcursorloader;
17 |
18 | import android.content.ContentResolver;
19 | import android.database.Cursor;
20 | import android.net.Uri;
21 | import android.os.Parcel;
22 | import android.os.Parcelable;
23 |
24 | import java.util.Arrays;
25 |
26 | import androidx.annotation.NonNull;
27 | import androidx.annotation.Nullable;
28 | import io.reactivex.BackpressureStrategy;
29 | import io.reactivex.Flowable;
30 | import io.reactivex.Observable;
31 | import io.reactivex.Observer;
32 | import io.reactivex.Scheduler;
33 | import io.reactivex.Single;
34 | import io.reactivex.disposables.Disposable;
35 | import io.reactivex.functions.Consumer;
36 | import io.reactivex.schedulers.Schedulers;
37 |
38 | /**
39 | * An RX replacement for {@link android.content.CursorLoader}
40 | *
41 | *
42 | * Usage:
43 | *
44 | * Create a {@link Query} using {@link Query.Builder}. The required parameter is only a content
45 | * URI.
46 | *
47 | * final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder()
48 | * .setContentUri(MediaStore.Audio.Media.INTERNAL_CONTENT_URI)
49 | * .setProjection(new String[]{MediaStore.Audio.Media._ID})
50 | * .setSortOrder(MediaStore.Audio.Artists.ARTIST)
51 | * .setSelection(MediaStore.Audio.Artists.ARTIST + "=?")
52 | * .setSelectionArgs(new String[] {"Oh Long Johnson"})
53 | * .create();
54 | * }
55 | *
56 | *
57 | * If you need to load only once, use {@link #single(ContentResolver, Query)}.
58 | *
59 | * If you need the loader to register ContentObserver and reload cursor passing it to onNext()
60 | * every time content changes, like {@link android.content.CursorLoader}, use
61 | * {@link #flowable(ContentResolver, Query, Scheduler, BackpressureStrategy)}.
62 | */
63 | public final class RxCursorLoader {
64 |
65 | static final String TAG = "RxCursorLoader";
66 |
67 | /**
68 | * Set this to true to enable debug logging
69 | */
70 | private static boolean LOG_DEBUG = false;
71 |
72 | /**
73 | * Used to enable/disable debug level logs.
74 | *
75 | * Disabled by default.
76 | */
77 | public static void setDebugLoggingEnabled(final boolean loggingEnabled) {
78 | LOG_DEBUG = loggingEnabled;
79 | }
80 |
81 | static boolean isDebugLoggingEnabled() {
82 | return LOG_DEBUG;
83 | }
84 |
85 | private RxCursorLoader() {
86 | throw new UnsupportedOperationException();
87 | }
88 |
89 | /**
90 | * @deprecated use {@link #observable(ContentResolver, Query, Scheduler)} instead.
91 | */
92 | @Deprecated
93 | @NonNull
94 | public static Observable create(
95 | @NonNull final ContentResolver resolver,
96 | @NonNull final Query query) {
97 | return observable(resolver, query, Schedulers.io());
98 | }
99 |
100 | /**
101 | * Create a new {@link Observable} that emits items from a {@link ContentResolver} query.
102 | * This acts like {@link android.content.CursorLoader}.
103 | *
104 | * When a non-null Cursor is loaded, it is passed to {@link Observer#onNext(Object)}}.
105 | *
106 | * If the query returns null, {@link QueryReturnedNullException} is passed to
107 | * {@link Observer#onError(Throwable)}.
108 | *
109 | * Every time the content changes, the Cursor will be reloaded and passed to {@link
110 | * Observer#onNext(Object)}.
111 | *
112 | * Make sure to close old cursor because cursors are not automatically closed
113 | *
114 | * {@link Observer#onError(Throwable)}} is called if {@link RuntimeException} is caught when running a
115 | * query.
116 | *
117 | * You must call {@link Disposable#dispose()} when finished.
118 | *
119 | *
120 | * protected void onStop() {
121 | * super.onStop();
122 | * // stop using Cursor and close it
123 | * mAdapter.changeCursor(null);
124 | * // Unsubscribe to stop monitoring for ContentObserver changes
125 | * mCursorDisposable.dispose();
126 | * }
127 | *
128 | *
129 | * @param resolver {@link ContentResolver} to use
130 | * @param query the {@link Query} to use
131 | * @param scheduler the {@link Scheduler} to emit items from. This will automatically set
132 | * {@link Observable#subscribeOn(Scheduler)} with this scheduler. Even if you change the
133 | * scheduler afterwards, the subsequent items will be still emitted from this scheduler.
134 | * @return new {@link Observable}.
135 | */
136 | @NonNull
137 | public static Observable observable(
138 | @NonNull final ContentResolver resolver,
139 | @NonNull final Query query,
140 | @NonNull final Scheduler scheduler) {
141 | return RxCursorLoaderFlowableFactory
142 | .create(resolver, query, scheduler, BackpressureStrategy.MISSING)
143 | .toObservable();
144 | }
145 |
146 | /**
147 | * Create a new {@link Flowable} that emits items from a {@link ContentResolver} query.
148 | * This acts like {@link android.content.CursorLoader}.
149 | *
150 | * When a non-null Cursor is loaded, it is passed to {@link Observer#onNext(Object)}}.
151 | *
152 | * If the query returns null, {@link QueryReturnedNullException} is passed to
153 | * {@link Observer#onError(Throwable)}.
154 | *
155 | * Every time the content changes, the Cursor will be reloaded and passed to {@link
156 | * Observer#onNext(Object)}.
157 | *
158 | * Make sure to close old cursor because cursors are not automatically closed
159 | *
160 | * {@link Observer#onError(Throwable)}} is called if {@link RuntimeException} is caught when running a
161 | * query.
162 | *
163 | * You must call {@link Disposable#dispose()} when finished.
164 | *
165 | *
166 | * protected void onStop() {
167 | * super.onStop();
168 | * // stop using Cursor and close it
169 | * mAdapter.changeCursor(null);
170 | * // Unsubscribe to stop monitoring for ContentObserver changes
171 | * mCursorDisposable.dispose();
172 | * }
173 | *
174 | *
175 | * @param resolver {@link ContentResolver} to use
176 | * @param query the {@link Query} to use
177 | * @param scheduler the {@link Scheduler} to emit items from. This will automatically set
178 | * {@link Flowable#subscribeOn(Scheduler)} with this scheduler. Even if you
179 | * change the
180 | * scheduler afterwards, the subsequent items will be still emitted from this
181 | * scheduler.
182 | * @param backpressureStrategy the {@link BackpressureStrategy} to use.
183 | * @return new {@link Flowable}.
184 | */
185 | @NonNull
186 | public static Flowable flowable(
187 | @NonNull final ContentResolver resolver,
188 | @NonNull final Query query,
189 | @NonNull final Scheduler scheduler,
190 | @NonNull final BackpressureStrategy backpressureStrategy) {
191 | return RxCursorLoaderFlowableFactory
192 | .create(resolver, query, scheduler, backpressureStrategy);
193 | }
194 |
195 | /**
196 | * Create a new {@link Single} that loads {@link Cursor} once and does not close it.
197 | * Calls {@link Consumer#accept(Object)} once non-null {@link Cursor} is loaded.
198 | * If the query returns null, {@link QueryReturnedNullException} is thrown.
199 | *
200 | * @param resolver {@link ContentResolver} to use
201 | * @param query the {@link Query} to use
202 | * @return new {@link Single}.
203 | */
204 | @NonNull
205 | public static Single single(
206 | @NonNull final ContentResolver resolver,
207 | @NonNull final Query query) {
208 | return RxCursorLoaderSingleFactory.single(resolver, query);
209 | }
210 |
211 | /**
212 | * Parameters for {@link RxCursorLoader}
213 | */
214 | public static final class Query implements Parcelable {
215 |
216 | Uri contentUri;
217 | String[] projection;
218 | String selection;
219 | String[] selectionArgs;
220 | String sortOrder;
221 |
222 | Query() {
223 |
224 | }
225 |
226 | Query(@NonNull final Parcel p) {
227 | contentUri = p.readParcelable(Uri.class.getClassLoader());
228 | projection = p.createStringArray();
229 | selection = p.readString();
230 | selectionArgs = p.createStringArray();
231 | sortOrder = p.readString();
232 | }
233 |
234 | @Override
235 | public void writeToParcel(@NonNull final Parcel p, final int i) {
236 | p.writeParcelable(contentUri, 0);
237 | p.writeStringArray(projection);
238 | p.writeString(selection);
239 | p.writeStringArray(selectionArgs);
240 | p.writeString(sortOrder);
241 | }
242 |
243 | @Override
244 | public int describeContents() {
245 | return 0;
246 | }
247 |
248 | // Generated by Android Studio
249 | @Override
250 | public boolean equals(final Object o) {
251 | if (this == o) {
252 | return true;
253 | }
254 | if (o == null || getClass() != o.getClass()) {
255 | return false;
256 | }
257 |
258 | final Query query = (Query) o;
259 |
260 | if (contentUri != null ? !contentUri.equals(query.contentUri)
261 | : query.contentUri != null) {
262 | return false;
263 | }
264 | // Probably incorrect - comparing Object[] arrays with Arrays.equals
265 | if (!Arrays.equals(projection, query.projection)) {
266 | return false;
267 | }
268 | if (selection != null ? !selection.equals(query.selection) : query.selection != null) {
269 | return false;
270 | }
271 | // Probably incorrect - comparing Object[] arrays with Arrays.equals
272 | //noinspection SimplifiableIfStatement
273 | if (!Arrays.equals(selectionArgs, query.selectionArgs)) {
274 | return false;
275 | }
276 | return sortOrder != null ? sortOrder.equals(query.sortOrder) : query.sortOrder == null;
277 |
278 | }
279 |
280 | // Generated by Android Studio
281 | @Override
282 | public int hashCode() {
283 | int result = contentUri != null ? contentUri.hashCode() : 0;
284 | result = 31 * result + Arrays.hashCode(projection);
285 | result = 31 * result + (selection != null ? selection.hashCode() : 0);
286 | result = 31 * result + Arrays.hashCode(selectionArgs);
287 | result = 31 * result + (sortOrder != null ? sortOrder.hashCode() : 0);
288 | return result;
289 | }
290 |
291 | @Override
292 | public String toString() {
293 | return "Params{" +
294 | "mContentUri=" + contentUri +
295 | ", mProjection=" + Arrays.toString(projection) +
296 | ", mSelection='" + selection + '\'' +
297 | ", mSelectionArgs=" + Arrays.toString(selectionArgs) +
298 | ", mSortOrder='" + sortOrder + '\'' +
299 | '}';
300 | }
301 |
302 | public static final Parcelable.Creator CREATOR = new Creator() {
303 |
304 | @Override
305 | public Query createFromParcel(final Parcel parcel) {
306 | return new Query(parcel);
307 | }
308 |
309 | @Override
310 | public Query[] newArray(final int size) {
311 | return new Query[size];
312 | }
313 | };
314 |
315 | /**
316 | * {@link Query} builder.
317 | *
318 | * The only required parameter is a content URI.
319 | */
320 | public static final class Builder {
321 |
322 | private Uri mContentUri;
323 | private String[] mProjection;
324 | private String mSelection;
325 | private String[] mSelectionArgs;
326 | private String mSortOrder;
327 |
328 | public Builder() {
329 |
330 | }
331 |
332 | @NonNull
333 | public Builder setContentUri(@NonNull final Uri contentUri) {
334 | mContentUri = contentUri;
335 | return this;
336 | }
337 |
338 | @NonNull
339 | public Builder setProjection(@Nullable final String[] projection) {
340 | mProjection = projection;
341 | return this;
342 | }
343 |
344 | @NonNull
345 | public Builder setSelection(@Nullable final String selection) {
346 | mSelection = selection;
347 | return this;
348 | }
349 |
350 | @NonNull
351 | public Builder setSelectionArgs(@Nullable final String[] selectionArgs) {
352 | mSelectionArgs = selectionArgs;
353 | return this;
354 | }
355 |
356 | @NonNull
357 | public Builder setSortOrder(@Nullable final String sortOrder) {
358 | mSortOrder = sortOrder;
359 | return this;
360 | }
361 |
362 | /**
363 | * Creates the {@link Query}
364 | *
365 | * @return the {@link Query}
366 | * @throws IllegalStateException if content uri is null
367 | */
368 | @NonNull
369 | public Query create() {
370 | if (mContentUri == null) {
371 | throw new IllegalStateException("Content URI not set");
372 | }
373 | final Query query = new Query();
374 | query.contentUri = mContentUri;
375 | query.projection = mProjection;
376 | query.selection = mSelection;
377 | query.selectionArgs = mSelectionArgs;
378 | query.sortOrder = mSortOrder;
379 | return query;
380 | }
381 | }
382 | }
383 | }
384 |
--------------------------------------------------------------------------------