Google is deprecating Android AsyncTask API in Android 11 and suggesting to use java.util.concurrent instead. you can check out the commit here
*
* #deprecated Use the standard <code>java.util.concurrent</code> or
* <a href="https://developer.android.com/topic/libraries/architecture/coroutines">
* Kotlin concurrency utilities</a> instead.
*/
#Deprecated
public abstract class AsyncTask<Params, Progress, Result> {
If you’re maintaining an older codebase with asynchronous tasks in Android, you’re likely going to have to change it in future. My question is that what should be proper replacement of the code snippet shown below using java.util.concurrent. It is a static inner class of an Activity. I am looking for something that will work with minSdkVersion 16
private static class LongRunningTask extends AsyncTask<String, Void, MyPojo> {
private static final String TAG = MyActivity.LongRunningTask.class.getSimpleName();
private WeakReference<MyActivity> activityReference;
LongRunningTask(MyActivity context) {
activityReference = new WeakReference<>(context);
}
#Override
protected MyPojo doInBackground(String... params) {
// Some long running task
}
#Override
protected void onPostExecute(MyPojo data) {
MyActivity activity = activityReference.get();
activity.progressBar.setVisibility(View.GONE);
populateData(activity, data) ;
}
}
You can directly use Executors from java.util.concurrent package.
I also searched about it and I found a solution in this Android Async API is Deprecated post.
Unfortunately, the post is using Kotlin, but after a little effort I have converted it into Java. So here is the solution.
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());
executor.execute(new Runnable() {
#Override
public void run() {
//Background work here
handler.post(new Runnable() {
#Override
public void run() {
//UI Thread work here
}
});
}
});
Pretty simple right? You can simplify it little more if you are using Java 8 in your project.
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());
executor.execute(() -> {
//Background work here
handler.post(() -> {
//UI Thread work here
});
});
Still, it cannot defeat kotlin terms of conciseness of the code, but better than the previous java version.
Hope this will help you. Thank You
private WeakReference<MyActivity> activityReference;
Good riddance that it's deprecated, because the WeakReference<Context> was always a hack, and not a proper solution.
Now people will have the opportunity to sanitize their code.
AsyncTask<String, Void, MyPojo>
Based on this code, Progress is actually not needed, and there is a String input + MyPojo output.
This is actually quite easy to accomplish without any use of AsyncTask.
public class TaskRunner {
private final Executor executor = Executors.newSingleThreadExecutor(); // change according to your requirements
private final Handler handler = new Handler(Looper.getMainLooper());
public interface Callback<R> {
void onComplete(R result);
}
public <R> void executeAsync(Callable<R> callable, Callback<R> callback) {
executor.execute(() -> {
final R result = callable.call();
handler.post(() -> {
callback.onComplete(result);
});
});
}
}
How to pass in the String? Like so:
class LongRunningTask implements Callable<MyPojo> {
private final String input;
public LongRunningTask(String input) {
this.input = input;
}
#Override
public MyPojo call() {
// Some long running task
return myPojo;
}
}
And
// in ViewModel
taskRunner.executeAsync(new LongRunningTask(input), (data) -> {
// MyActivity activity = activityReference.get();
// activity.progressBar.setVisibility(View.GONE);
// populateData(activity, data) ;
loadingLiveData.setValue(false);
dataLiveData.setValue(data);
});
// in Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
viewModel.loadingLiveData.observe(this, (loading) -> {
if(loading) {
progressBar.setVisibility(View.VISIBLE);
} else {
progressBar.setVisibility(View.GONE);
}
});
viewModel.dataLiveData.observe(this, (data) -> {
populateData(data);
});
}
This example used a single-threaded pool which is good for DB writes (or serialized network requests), but if you want something for DB reads or multiple requests, you can consider the following Executor configuration:
private static final Executor THREAD_POOL_EXECUTOR =
new ThreadPoolExecutor(5, 128, 1,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
One of the simplest alternative is to use Thread
new Thread(new Runnable() {
#Override
public void run() {
// do your stuff
runOnUiThread(new Runnable() {
public void run() {
// do onPostExecute stuff
}
});
}
}).start();
If your project supports JAVA 8, you can use lambda:
new Thread(() -> {
// do background stuff here
runOnUiThread(()->{
// OnPostExecute stuff here
});
}).start();
According to the Android documentation AsyncTask was deprecated in API level 30 and it is suggested to use the standard java.util.concurrent or Kotlin concurrency utilities instead.
Using the latter it can be achieved pretty simple:
Create generic extension function on CoroutineScope:
fun <R> CoroutineScope.executeAsyncTask(
onPreExecute: () -> Unit,
doInBackground: () -> R,
onPostExecute: (R) -> Unit
) = launch {
onPreExecute() // runs in Main Thread
val result = withContext(Dispatchers.IO) {
doInBackground() // runs in background thread without blocking the Main Thread
}
onPostExecute(result) // runs in Main Thread
}
Use the function with any CoroutineScope which has Dispatchers.Main context:
In ViewModel:
class MyViewModel : ViewModel() {
fun someFun() {
viewModelScope.executeAsyncTask(onPreExecute = {
// ... runs in Main Thread
}, doInBackground = {
// ... runs in Worker(Background) Thread
"Result" // send data to "onPostExecute"
}, onPostExecute = {
// runs in Main Thread
// ... here "it" is the data returned from "doInBackground"
})
}
}
In Activity or Fragment:
lifecycleScope.executeAsyncTask(onPreExecute = {
// ... runs in Main Thread
}, doInBackground = {
// ... runs in Worker(Background) Thread
"Result" // send data to "onPostExecute"
}, onPostExecute = {
// runs in Main Thread
// ... here "it" is the data returned from "doInBackground"
})
To use viewModelScope or lifecycleScope add next line(s) to dependencies of the app's build.gradle file:
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$LIFECYCLE_VERSION" // for viewModelScope
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$LIFECYCLE_VERSION" // for lifecycleScope
At the time of writing final LIFECYCLE_VERSION = "2.3.0-alpha05"
UPDATE:
Also we can implement progress updating using onProgressUpdate function:
fun <P, R> CoroutineScope.executeAsyncTask(
onPreExecute: () -> Unit,
doInBackground: suspend (suspend (P) -> Unit) -> R,
onPostExecute: (R) -> Unit,
onProgressUpdate: (P) -> Unit
) = launch {
onPreExecute()
val result = withContext(Dispatchers.IO) {
doInBackground {
withContext(Dispatchers.Main) { onProgressUpdate(it) }
}
}
onPostExecute(result)
}
Using any CoroutineScope (viewModelScope/lifecycleScope, see implementations above) with Dispatchers.Main context we can call it:
someScope.executeAsyncTask(
onPreExecute = {
// ... runs in Main Thread
}, doInBackground = { publishProgress: suspend (progress: Int) -> Unit ->
// ... runs in Background Thread
// simulate progress update
publishProgress(50) // call `publishProgress` to update progress, `onProgressUpdate` will be called
delay(1000)
publishProgress(100)
"Result" // send data to "onPostExecute"
}, onPostExecute = {
// runs in Main Thread
// ... here "it" is a data returned from "doInBackground"
}, onProgressUpdate = {
// runs in Main Thread
// ... here "it" contains progress
}
)
Use this class to execute background task in Background Thread this class is work for all android API version include Android 11 also this code is same work like AsyncTask with doInBackground and onPostExecute methods
public abstract class BackgroundTask {
private Activity activity;
public BackgroundTask(Activity activity) {
this.activity = activity;
}
private void startBackground() {
new Thread(new Runnable() {
public void run() {
doInBackground();
activity.runOnUiThread(new Runnable() {
public void run() {
onPostExecute();
}
});
}
}).start();
}
public void execute(){
startBackground();
}
public abstract void doInBackground();
public abstract void onPostExecute();
}
After copying the above class, you can then use it with this:
new BackgroundTask(MainActivity.this) {
#Override
public void doInBackground() {
//put you background code
//same like doingBackground
//Background Thread
}
#Override
public void onPostExecute() {
//hear is result part same
//same like post execute
//UI Thread(update your UI widget)
}
}.execute();
Android deprecated AsyncTask API in Android 11 to get rid of a share of problems to begin with.
So, what's now?
Threads
Executers
RxJava
Listenable Futures
Coroutines 🔥
Why Coroutines?
Coroutines are the Kotlin way to do asynchronous programming. Compiler
support is stable since Kotlin 1.3, together with a
kotlinx.coroutines library -
Structured Concurrency
Non-blocking, sequential code
Cancellation propagation
Natural Exception Handling
Here I created a Alternative for AsyncTask using Coroutines which can be used same as AsyncTask without changing much code base in your project.
Create a new Abstract class AsyncTaskCoroutine which takes input parameter and output parameter datatypes of-course these parameters are optional :)
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
abstract class AsyncTaskCoroutine<I, O> {
var result: O? = null
//private var result: O
open fun onPreExecute() {}
open fun onPostExecute(result: O?) {}
abstract fun doInBackground(vararg params: I): O
fun <T> execute(vararg input: I) {
GlobalScope.launch(Dispatchers.Main) {
onPreExecute()
callAsync(*input)
}
}
private suspend fun callAsync(vararg input: I) {
GlobalScope.async(Dispatchers.IO) {
result = doInBackground(*input)
}.await()
GlobalScope.launch(Dispatchers.Main) {
onPostExecute(result)
}
}
}
2 . Inside Activity use this as same as your old AsycnTask now
new AsyncTaskCoroutine() {
#Override
public Object doInBackground(Object[] params) {
return null;
}
#Override
public void onPostExecute(#Nullable Object result) {
}
#Override
public void onPreExecute() {
}
}.execute();
InCase if you need to send pass params
new AsyncTaskCoroutine<Integer, Boolean>() {
#Override
public Boolean doInBackground(Integer... params) {
return null;
}
#Override
public void onPostExecute(#Nullable Boolean result) {
}
#Override
public void onPreExecute() {
}
}.execute();
Google recommends using Java’s Concurrency framework or Kotlin Coroutines. but Rxjava end to have much more flexibility and features then java concurrency so gained quite a bit of popularity.
I actually wrote two Medium stories about it:
AsyncTas is deprecated now what
AsyncTas is deprecated now what part 2
The first one is with Java and a workaround with Runnable, the second is a Kotlin and coroutines solution.
Both are with code examples of course.
The accepted answer is good. But...
I didn't see cancel() method implementation
So my implementation with possibility to cancel the running task (simulating cancellation) is below.
Cancel is needed to not run postExecute() method in case of task interruption.
public abstract class AsyncTaskExecutor<Params> {
public static final String TAG = "AsyncTaskRunner";
private static final Executor THREAD_POOL_EXECUTOR =
new ThreadPoolExecutor(5, 128, 1,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
private final Handler mHandler = new Handler(Looper.getMainLooper());
private boolean mIsInterrupted = false;
protected void onPreExecute(){}
protected abstract Void doInBackground(Params... params);
protected void onPostExecute(){}
protected void onCancelled() {}
#SafeVarargs
public final void executeAsync(Params... params) {
THREAD_POOL_EXECUTOR.execute(() -> {
try {
checkInterrupted();
mHandler.post(this::onPreExecute);
checkInterrupted();
doInBackground(params);
checkInterrupted();
mHandler.post(this::onPostExecute);
} catch (InterruptedException ex) {
mHandler.post(this::onCancelled);
} catch (Exception ex) {
Log.e(TAG, "executeAsync: " + ex.getMessage() + "\n" + Debug.getStackTrace(ex));
}
});
}
private void checkInterrupted() throws InterruptedException {
if (isInterrupted()){
throw new InterruptedException();
}
}
public void cancel(boolean mayInterruptIfRunning){
setInterrupted(mayInterruptIfRunning);
}
public boolean isInterrupted() {
return mIsInterrupted;
}
public void setInterrupted(boolean interrupted) {
mIsInterrupted = interrupted;
}
}
Example of using this class:
public class MySearchTask extends AsyncTaskExecutor<String> {
public MySearchTask(){
}
#Override
protected Void doInBackground(String... params) {
// Your long running task
return null;
}
#Override
protected void onPostExecute() {
// update UI on task completed
}
#Override
protected void onCancelled() {
// update UI on task cancelled
}
}
MySearchTask searchTask = new MySearchTask();
searchTask.executeAsync("Test");
Here I also created an Alternative for AsyncTask using abstract class and it can be just copied as a class.
/app/src/main/java/../AsyncTasks.java
public abstract class AsyncTasks {
private final ExecutorService executors;
public AsyncTasks() {
this.executors = Executors.newSingleThreadExecutor();
}
private void startBackground() {
onPreExecute();
executors.execute(new Runnable() {
#Override
public void run() {
doInBackground();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
onPostExecute();
}
});
}
});
}
public void execute() {
startBackground();
}
public void shutdown() {
executors.shutdown();
}
public boolean isShutdown() {
return executors.isShutdown();
}
public abstract void onPreExecute();
public abstract void doInBackground();
public abstract void onPostExecute();
}
Implementation/ use of the above class
new AsyncTasks() {
#Override
public void onPreExecute() {
// before execution
}
#Override
public void doInBackground() {
// background task here
}
#Override
public void onPostExecute() {
// Ui task here
}
}.execute();
My custom replacement: https://github.com/JohnyDaDeveloper/AndroidAsync
It only works when the app is running (more specifically the activity which scheduled the task), but it's capable of updating the UI after the background task was completed
EDIT: My AsyncTask no longer reqires Activiy to function.
Just replace the whole class with this Thread and put it in a method to pass variables
new Thread(() -> {
// do background stuff here
runOnUiThread(()->{
// OnPostExecute stuff here
});
}).start();
and in Fragment add the Context to the runOnUiThread() methode:
new Thread(() -> {
// do background stuff here
context.runOnUiThread(()->{
// OnPostExecute stuff here
});
}).start();
You can use this custom class as an alternative of the AsyncTask<>, this is the same as AsyncTask so you not need to apply extra efforts for the same.
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TaskRunner {
private static final int CORE_THREADS = 3;
private static final long KEEP_ALIVE_SECONDS = 60L;
private static TaskRunner taskRunner = null;
private Handler handler = new Handler(Looper.getMainLooper());
private ThreadPoolExecutor executor;
private TaskRunner() {
executor = newThreadPoolExecutor();
}
public static TaskRunner getInstance() {
if (taskRunner == null) {
taskRunner = new TaskRunner();
}
return taskRunner;
}
public void shutdownService() {
if (executor != null) {
executor.shutdown();
}
}
public void execute(Runnable command) {
executor.execute(command);
}
public ExecutorService getExecutor() {
return executor;
}
public <R> void executeCallable(#NonNull Callable<R> callable, #NonNull OnCompletedCallback<R> callback) {
executor.execute(() -> {
R result = null;
try {
result = callable.call();
} catch (Exception e) {
e.printStackTrace(); // log this exception
} finally {
final R finalResult = result;
handler.post(() -> callback.onComplete(finalResult));
}
});
}
private ThreadPoolExecutor newThreadPoolExecutor() {
return new ThreadPoolExecutor(
CORE_THREADS,
Integer.MAX_VALUE,
KEEP_ALIVE_SECONDS,
TimeUnit.SECONDS,
new SynchronousQueue<>()
);
}
public interface OnCompletedCallback<R> {
void onComplete(#Nullable R result);
}
}
How to use it? Please follow the below examples.
With lambda expressions
TaskRunner.getInstance().executeCallable(() -> 1, result -> {
});
TaskRunner.getInstance().execute(() -> {
});
Without lambda expressions
TaskRunner.getInstance().executeCallable(new Callable<Integer>() {
#Override
public Integer call() throws Exception {
return 1;
}
}, new TaskRunner.OnCompletedCallback<Integer>() {
#Override
public void onComplete(#Nullable Integer result) {
}
});
TaskRunner.getInstance().execute(new Runnable() {
#Override
public void run() {
}
});
Note: Don't forget to shutdown executors service
TaskRunner.getInstance().shutdownService();
You can migrate to next approaches depends your needs
Thread + Handler
Executor
Future
IntentService
JobScheduler
RxJava
Coroutines (Kotlin)
[Android async variants]
My answer is similar to the others, but it is easier to read imo.
This is the class:
public class Async {
private static final ExecutorService executorService = Executors.newCachedThreadPool();
private static final Handler handler = new Handler(Looper.getMainLooper());
public static <T> void execute(Task<T> task) {
executorService.execute(() -> {
T t = task.doAsync();
handler.post(() -> {
task.doSync(t);
});
});
}
public interface Task<T> {
T doAsync();
void doSync(T t);
}
}
And here's an example on how to use it:
String url;
TextView responseCodeText;
Async.execute(new Async.Task<Integer>() {
#Override
public Integer doAsync() {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
return connection.getResponseCode();
} catch (IOException e) {
return null;
}
}
#Override
public void doSync(Integer responseCode) {
responseCodeText.setText("responseCode=" + responseCode);
}
});
This is my code
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public abstract class AsyncTaskRunner<T> {
private ExecutorService executorService = null;
private Set<Callable<T>> tasks = new HashSet<>();
public AsyncTaskRunner() {
this.executorService = Executors.newSingleThreadExecutor();
}
public AsyncTaskRunner(int threadNum) {
this.executorService = Executors.newFixedThreadPool(threadNum);
}
public void addTask(Callable<T> task) {
tasks.add(task);
}
public void execute() {
try {
List<Future<T>> features = executorService.invokeAll(tasks);
List<T> results = new ArrayList<>();
for (Future<T> feature : features) {
results.add(feature.get());
}
this.onPostExecute(results);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
this.onCancelled();
} finally {
executorService.shutdown();
}
}
protected abstract void onPostExecute(List<T> results);
protected void onCancelled() {
// stub
}
}
And usage example.
Extends the AsyncTaskRunner class,
class AsyncCalc extends AsyncTaskRunner<Integer> {
public void addRequest(final Integer int1, final Integer int2) {
this.addTask(new Callable<Integer>() {
#Override
public Integer call() throws Exception {
// Do something in background
return int1 + int2;
}
});
}
#Override
protected void onPostExecute(List<Integer> results) {
for (Integer answer: results) {
Log.d("AsyncCalc", answer.toString());
}
}
}
then use it!
AsyncCalc calc = new AsyncCalc();
calc.addRequest(1, 2);
calc.addRequest(2, 3);
calc.addRequest(3, 4);
calc.execute();
AsyncTask class does not seem to be removed any time soon, but we did simply un-deprecate it anyway, because:
We didn't want to add lots of suppress annotations.
The alternative solutions have too much boiler-plate, or in most cases, without any real advantage vs AsyncTask.
We did not want to re-invent the wheel.
We didn't want to fear the day it will finally be removed.
Refactoring takes too much time.
Example
Simply add below file to your project, then search for "android.os.AsyncTask" imports, and replase all to the packge you did choose for said file.
As you may already know, this is no big deal, and is basically what the well known AndroidX library does all the time.
Get AsyncTask.java file at: https://gist.github.com/top-master/0efddec3e2c35d77e30331e8c3bc725c
Docs says:
AsyncTask This class was deprecated in API level 30. Use the standard
java.util.concurrent or Kotlin concurrency utilities instead.
You need to use Handler or coroutines instead AsyncTask.
Use Handler for Java
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
// Your Code
}
}, 3000);
Use Handler for Kotlin
Handler(Looper.getMainLooper()).postDelayed({
// Your Code
}, 3000)
when I run below code if I don't write observeOn line, app crashes because getView().showBlockLayout(isBlock); invoke a method that try to hide or show a layout.
but I tried to change below observeOn(AndroidSchedulers.mainThread()) to subscribeOn(AndroidSchedulers.mainThread()) and app crashes again!
subscription.add(UserStore.getInstance().getBlockObservable(databaseHelper.getConference().getUserChatId())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
#Override
public void call(Boolean isBlock) {
getView().showBlockLayout(isBlock);
databaseHelper.getConference().setBlock(isBlock);
mConferenceModel.setBlock(isBlock);
}
}));
I also test this:
subscription.add(UserStore.getInstance().getBlockObservable(databaseHelper.getConference().getUserChatId())
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
#Override
public void call(Boolean isBlock) {
getView().showBlockLayout(isBlock);
databaseHelper.getConference().setBlock(isBlock);
mConferenceModel.setBlock(isBlock);
}
}));
and unexpectedly it worked and did not crash! I didn't use subscribeOn in getBlockObservable method(because I know we can set it once)
it's my UserStore class
PublishSubject<Pair<String,Boolean>> mObservableBlock;
private UserStore(){
mObservableBlock = PublishSubject.create();
mInstance = this;
}
public static UserStore getInstance() {
if(mInstance == null)
new UserStore();
return mInstance;
}
public Observable<Boolean> getBlockObservable(final String userId){
return mObservableBlock
.observeOn(Schedulers.computation())
.filter(new Func1<Pair<String,Boolean>, Boolean>() {
#Override
public Boolean call(Pair<String,Boolean> s) {
if(userId.equals(s.first))
return true;
return false;
}
}).map(new Func1< Pair<String, Boolean>, Boolean>() {
#Override
public Boolean call(Pair<String, Boolean> UserBlock) {
return UserBlock.second;
}
});
}
public void publishBlockedUser(String userId,boolean isBlock){
mObservableBlock.onNext(new Pair<String, Boolean>(userId,isBlock));
}
and here is how I imported rxjava dependency in gradle
compile 'io.reactivex:rxjava:1.1.5'
compile 'io.reactivex:rxandroid:1.2.0'
As mentioned in this medium artice:
One important fact is that subscribeOn does not work with Subjects.
So you can't use subscribeOn with subjects and we have to use observerOn(AndroidSchedulers.mainThread()) before subscription.
so all downstream methods are called on mainThread after that.
check this medium artice
I'm fairly new to RxJava so I was hoping someone with a bit more knowledge could tear apart my method for getting a Flowable from a RealmResults, maintaining a reference to the resource for the lifetime of the Flowable and then disposing of it at the end. I'd be interested to know any errors I've made. The motivation behind this was to be able to subscribe to live realm queries without exposing Realm to the rest of the app.
One thing I'm not too keen on is that the Realm instance is passed into the function and then the Flowable manages closing it, rather than the caller managing closing it, but I can't see a way of closing the Realm instance in the calling class without either maintaining a seperate reference to it or wrapping the whole thing in another Flowable.using which seems a bit ugly.
public class RxRealm {
private static class ResultsResource<T extends RealmModel> {
final Realm realm;
final RealmResults<T> results;
ResultsResource(Realm realm, RealmResults<T> results) {
this.realm = realm;
this.results = results;
}
}
public static <T extends RealmModel> Flowable<RealmResults<T>> asFlowable(final Realm realm, final RealmResults<T> results) {
return Flowable.using(new Callable<ResultsResource>() {
#Override
public ResultsResource call() throws Exception {
return new ResultsResource<>(realm, results);
}
}, new Function<ResultsResource, Publisher<? extends RealmResults<T>>>() {
#Override
public Publisher<? extends RealmResults<T>> apply(#NonNull ResultsResource resultsResource) throws Exception {
return Flowable.create(new FlowableOnSubscribe<RealmResults<T>>() {
#Override
public void subscribe(#NonNull final FlowableEmitter<RealmResults<T>> emitter) throws Exception {
final RealmChangeListener<RealmResults<T>> changeListener = new RealmChangeListener<RealmResults<T>>() {
#Override
public void onChange(RealmResults<T> element) {
if (!emitter.isCancelled()) {
emitter.onNext(element);
}
}
};
results.addChangeListener(changeListener);
}
}, BackpressureStrategy.LATEST);
}
}, new Consumer<ResultsResource>() {
#Override
public void accept(#NonNull ResultsResource resource) throws Exception {
resource.results.removeAllChangeListeners();
resource.realm.close();
}
});
}
}
Usage:
public Flowable<Integer> getUnreadMessages(final String matchingId) {
Realm realm = Realm.getDefaultInstance();
RealmQuery<Message> query = realm.where(Message.class)
.equalTo("read", false);
if (matchingId != null) {
query.equalTo("id", matchingId);
}
RealmResults<Message> results = query.findAllAsync();
return RxRealm.asFlowable(realm, results)
.map(new Function<RealmResults<Message>, Integer>() {
#Override
public Integer apply(#NonNull RealmResults<Message> realmResults) throws Exception {
return realmResults.size();
}
});
}
I have the following RxJava Observable:
final class MapBitmapObservable {
static Observable<Bitmap> create(#NonNull final MapView mapView) {
return Observable.create(new Observable.OnSubscribe<Bitmap>() {
#Override
public void call(final Subscriber<? super Bitmap> subscriber) {
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull final GoogleMap googleMap) {
googleMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(#Nullable final Bitmap bitmap) {
if (bitmap != null) {
subscriber.onNext(bitmap);
subscriber.onCompleted();
} else {
subscriber.onError(new MapSnapshotFailedException());
}
}
});
}
});
}
});
}
private MapBitmapObservable() {
}
}
The MapView method getMapAsync must be called on the main thread to avoid this exception:
java.lang.IllegalStateException: getMapAsync() must be called on the main thread
at com.google.android.gms.common.internal.zzx.zzcD(Unknown Source)
at com.google.android.gms.maps.MapView.getMapAsync(Unknown Source)
at com.github.stkent.bugshaker.email.screenshot.maps.MapBitmapObservable$1.call(MapBitmapObservable.java:42)
at com.github.stkent.bugshaker.email.screenshot.maps.MapBitmapObservable$1.call(MapBitmapObservable.java:37)
at rx.Observable.unsafeSubscribe(Observable.java:8098)
...
Assume the MapBitmapObservable is used as part of an Observable chain in which previous and subsequent operations are potentially long-running and should be executed off the main thread. A simplified example could look like this:
Observable.just(activity)
.flatmap(new Func1<Activity, Observable<MapView>>() {
#Override
public Observable<Bitmap> call(#NonNull final Activity activity) {
return ExpensiveToCreateObservable.create(activity);
}
})
.flatmap(new Func1<MapView, Observable<Bitmap>>() {
#Override
public Observable<Bitmap> call(#NonNull final MapView mapView) {
return MapBitmapObservable.create(mapView);
}
})
.flatmap(new Func1<Bitmap, Observable<Uri>>() {
#Override
public Observable<Uri> call(#NonNull final Bitmap bitmap) {
return SomeOtherExpensiveToCreateObservable.create(bitmap);
}
})
.subscribeOn(Schedulers.io())
.subscribe();
(although it should be noted that in my actual application, the chaining is spread across several different methods). I would like to:
make sure that MapView.getMapAsync is called on the main thread;
allow the second long-running operation to execute on the original Scheduler, whatever that may have been (Schedulers.io(), Schedulers.computation(), etc.)
In my mind, pseudocode to achieve this would look something like:
Observable.just(activity)
.flatmap(new Func1<Activity, Observable<MapView>>() {
#Override
public Observable<Bitmap> call(#NonNull final Activity activity) {
return ExpensiveToCreateObservable.create(activity);
}
})
.observeOn(AndroidSchedulers.mainThread()) // This is real, and resolves bullet 1.
.flatmap(new Func1<MapView, Observable<Bitmap>>() {
#Override
public Observable<Bitmap> call(#NonNull final MapView mapView) {
return MapBitmapObservable.create(mapView);
}
})
.observeOn(/* Some way of referencing the thread on which I originally subscribed, to resolve bullet 2. */)
.flatmap(new Func1<Bitmap, Observable<Uri>>() {
#Override
public Observable<Uri> call(#NonNull final Bitmap bitmap) {
return SomeOtherExpensiveToCreateObservable.create(bitmap);
}
})
.subscribeOn(Schedulers.io()) // I do not want to rely on knowledge of the Scheduler type used at this call-site.
.subscribe();
Is this possible?
From the observeOn() documentation:
ObserveOn, on the other hand, affects the thread that the Observable will use below where that operator appears. For this reason, you may call ObserveOn multiple times at various points during the chain of Observable operators in order to change on which threads certain of those operators operate.
So as mentioned by Aaron He, you could keep some reference to the Scheduler you are using use it on the latter "observeOn".
Another approach to do this that I sometimes use, is to remove both "observeOn" function, and make sure View items are being handled on UI thread by Activity.runOnUiThread. Something like -
static Observable<Bitmap> create(#NonNull final Activity activity,#NonNull final SomeObject someObject) {
return Observable.create(new Observable.OnSubscribe<Pair<Activity,SomeObject>>() {
#Override
public void call(final Subscriber<? super Pair<Activity,SomeObject>> subscriber) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
someObject.doStuff();
}
});
}
});
}