简体   繁体   中英

How to get values from an AsyncTask when it is in another class

I need to get the result from my AsyncTask. I can actually get the result from the task but I just don't know how to get it from the method that needs it. As will see, the AsyncTask is in a different class. If you have a question so I can clarify, please tell me so I can edit the post. See my code below:

public class UserRepository {
    private UserDao userDao;
    private User user;
    private LiveData<List<User>> allUsers;

    public UserRepository(Application application) {
        AtsDatabase database = AtsDatabase.getInstance(application);
        userDao = database.userDao();
        allUsers = userDao.getUsers();
    }

 private MutableLiveData<User> userSearched = new MutableLiveData<>();
 private void asyncFinished(User userResult) {
    if(userResult == null) return;
    Log.i("TAG", "asyncFinished: " + userResult.getLastName());
    userSearched.setValue(userResult);
 }

    public LiveData<User> getUserByUserName(String userName) {
        new GetUserByUserNameAsyncTask(userDao).execute(userName); ===> I NEED THE RESULT HERE SO I CAN PASS IT TO MY VIEW MODEL
    }

    public LiveData<List<User>> getAllUsers() { return allUsers; }

    private static class InsertUserAsyncTask extends AsyncTask<User, Void, Void> {
        private UserDao userDao;

        private InsertUserAsyncTask(UserDao userDao) { this.userDao = userDao; }

        @Override
        protected Void doInBackground(User... users) {
            userDao.insert(users[0]);
            return null;
        }
    }

    private static class GetUserByUserNameAsyncTask extends AsyncTask<String, Void, User> {
        private LiveData<User> user;
        private UserDao userDao;

        private GetUserByUserNameAsyncTask(UserDao userDao) { this.userDao = userDao; }

        @Override
        protected User doInBackground(String... strings) {
             user = userDao.getUserByUserName(strings[0]); ======> I GET RESULT HERE 
             return null;
        }

         @Override
        protected void onPostExecute(User user) {
        super.onPostExecute(user);
        Log.i("TAG", "onPostExecute: "+user.getLastName());
        delegate.asyncFinished(user);
    }
    }
}

How do I make this right? Thank you.

First of all, AsyncTask is now deprecated.

If you still want to use it, create a MutableLiveData and return it as a LiveData in the exposed function, then pass it through the constructor of the AsyncTask . Use the postValue method of the MutableLiveData to set the result after you get it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM