0

I have this method that is using the deprecated module AsyncTask:

private void createNewNote() {
        AsyncTask<ContentValues, Void, Uri> task = new AsyncTask<ContentValues, Void, Uri>() {
            @Override
            protected Uri doInBackground(ContentValues... params) {
               ContentValues insertValues = params[0];
               Uri rowUri = getContentResolver().insert(Notes.CONTENT_URI, insertValues);
               return rowUri;
            }
            @Override
            protected void onPostExecute(Uri uri) {
                mNoteUri = uri;
            }
        };

        ContentValues values = new ContentValues();
        values.put(Notes.COLUMN_COURSE_ID, "");
        values.put(Notes.COLUMN_NOTE_TITLE, "");
        values.put(Notes.COLUMN_NOTE_TEXT, "");

        task.execute(values);
    }

I would like to use a modern module instead of AsyncTask. I tried using

ExecutorService executor = Executors.newSingleThreadExecutor();

but the thing is I need to return a value from the Background task to the Main thread, and I didn't manage to do it with newSingleThreadExecutor. Do you have any solutions? (I want to keep things as close as possible to the actual solution).

nolwww
  • 1,355
  • 1
  • 15
  • 33
  • Is this for android? Then maybe check https://stackoverflow.com/questions/58767733/android-asynctask-api-deprecating-in-android-11-what-are-the-alternatives ... otherwise, look at concepts such as futures (https://www.baeldung.com/java-future) – GhostCat Jan 20 '21 at 08:16
  • Yes I checked this question actually. But the difference here is that I pass a value between doInBackground and onPostExecute – nolwww Jan 20 '21 at 08:20
  • You still didnt say if you are asking for Android specifically. – GhostCat Jan 20 '21 at 08:34
  • Sorry, yes I am, I will update the question – nolwww Jan 20 '21 at 08:35

1 Answers1

0

You can using Coroutines and suspend function with Kotlin.

suspend fun fetchData(): YourResponse {
     // make network call
     // return your response
}

then you can using in activity or fragment like this:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    GlobalScope.launch(Dispatchers.Main) {
        val data = fetchData() // fetch on IO thread
        showData(data) // back on UI thread
    }
    
}

Dispatchers.Main handle in UI thread. If you familiar with MVVM you can using ViewModel, you can use viewmodelscope.launch and listen data change with LiveData

For more information: https://developer.android.com/kotlin/coroutines

Tungken
  • 1,917
  • 1
  • 15
  • 18