N
N
Nicholas Unknown2019-11-21 20:53:19
Java
Nicholas Unknown, 2019-11-21 20:53:19

How to transfer data from a thread to the main thread without slowing down the main thread?

Hello. I'm learning java ee, I made a primitive server part and now I'm taking up a primitive client part. I am writing a client for android, trying to implement the MVVM architecture
And so, let's get started.
Available classes MainActivity, MainViewModel, ServerHandler.
The activity contains a reference to the mainViewModel object and a button in onClick() which calls the mainViewModel.LoadData() method;
MainViewModel contains a RequestHandler object and a LoadData() method;
ServerHandler contains fields for working with requests and an internal class RequestExecutor implements Runnable
The task of ServerHandler is to be responsible for connecting to the server, generating requests, processing responses.
The task of the RequestExecutor is to receive the request object and actually execute the request and return a response.
To work with Http I use OkHttp;
In general, if I don’t use multithreading, then when the activity makes a request to the viewModel for data, and that in turn tries to load them from the server, then the UI thread hangs until the end of the request logic.
If I use multithreading, then when I get the Responce object inside the RequestExecutor, I will not have the slightest idea how I now have the answer, give the data from the response to the viewModel and what would the viewModel tell the activity after that that the data has arrived.
Question to respected experts: How can I correctly implement the operation of asynchronous data transfer to the main thread without slowing down the main thread in MVVM?
I am a beginner in this topic, please don't throw stones.
If you have options for a different implementation, I will be glad to listen, because I have no idea how to properly implement such actions.
I am attaching the code.
MainActivity

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.clientapp.R;
import com.example.clientapp.viewmodel.MainViewModel;

public class MainActivity extends AppCompatActivity {

    private MainViewModel viewModel;

    private TextView outputText;
    private ProgressBar loadingProgress;
    private Button loadButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    private void init() {
        viewModel = ViewModelProviders.of(this).get(MainViewModel.class);

        outputText = findViewById(R.id.output_textview);
        loadingProgress = findViewById(R.id.loading_progress);
        loadButton = findViewById(R.id.load_button);
    }


    public void LoadDataOnClick(View view) {
        loadButton.setEnabled(false);
        loadingProgress.setVisibility(View.VISIBLE);

       viewModel.LoadText();
    }
}

MainViewModel
package com.example.clientapp.viewmodel;

import androidx.lifecycle.ViewModel;

import com.example.clientapp.ServerHandler;

public class MainViewModel extends ViewModel {

    ServerHandler serverHandler;

    public MainViewModel() {
        this.serverHandler = ServerHandler.getInstance();
    }


    public void LoadText(){
         serverHandler.loadData();
    }
}

ServerHandler
package com.example.clientapp;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ServerHandler {

    private final String GET_DATA_URL = "http://192.168.8.100:8080/app";

    private static ServerHandler handler;

    private OkHttpClient client;

    private ServerHandler() {
        client = new OkHttpClient.Builder().cookieJar(new CookieJar() {

            private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();

            @Override
            public void saveFromResponse(@NotNull HttpUrl url, @NotNull List<Cookie> cookies) {
                cookieStore.put(url, cookies);
            }

            @NotNull
            @Override
            public List<Cookie> loadForRequest(@NotNull HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url);
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        }).build();
    }

    public static ServerHandler getInstance() {
        if (handler == null) handler = new ServerHandler();
        return handler;
    }


    public void loadData() {

        Request request = new Request.Builder()
                .url(GET_DATA_URL)
                .build();


        Thread requestThread = new Thread(new RequestExecutor(request));


    }


  class RequestExecutor implements Runnable{

        Request request;

      public RequestExecutor(Request request) {
          this.request = request;
      }

      @Override
      public void run() {
          client.newCall(request).enqueue(new Callback() {
              @Override
              public void onFailure(@NotNull Call call, @NotNull IOException e) {

              }

              @Override
              public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                  //What should i do here?
              }
          });
      }
  }

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-11-21
@sergey-gornostaev

1011787554.jpg

T
terminator-light, 2019-11-21
@terminator-light

Use RxJava for threading, Retrofit with OkHttp for networking
How do I build MVVM architecture logic in my application?
Consuming REST API using Retrofit Library with the...
The Missing Google Sample of Android “Architecture...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question