Skip to content

Simple Async

Yuri Shmakov edited this page Aug 14, 2017 · 4 revisions

MainActivit.java:

public class MainActivity extends MvpAppCompatActivity implements HelloWorldView {
	@InjectPresenter
	HelloWorldPresenter mHelloWorldPresenter;

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

	@Override
	public void showMessage(int message) {
		TextView messageTextView = new TextView(this);
		messageTextView.setText(message);
		messageTextView.setTextSize(40);
		messageTextView.setGravity(Gravity.CENTER_HORIZONTAL);
		((ViewGroup) findViewById(R.id.activity_main)).addView(messageTextView);
	}
}

HelloWorldPresenter.java:

@InjectViewState
public class HelloWorldPresenter extends MvpPresenter<HelloWorldView> {
	public HelloWorldPresenter() {
		AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... voids) {
				sleepSecond();
				return null;
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				getViewState().showMessage(R.string.hello_world);
			}

			private void sleepSecond() {
				try {
					TimeUnit.SECONDS.sleep(3);
				} catch (InterruptedException ignore) {}
			}
		};

		asyncTask.execute();
	}
}

HelloWorldView.java:

public interface HelloWorldView extends MvpView {
	void showMessage(int message);
}
Screen video capture