android / architecture-components-samples

Samples for Android Architecture Components.
https://d.android.com/arch
Apache License 2.0
23.42k stars 8.29k forks source link

[Question] All requests are GET, what about Post? #102

Closed amrro closed 7 years ago

amrro commented 7 years ago

TL;DR: How to use POSTinstead of GET?

Thanks for your effort, really great learning experience browsing your code. But I have small question.

What I've noticed that all requests in GithubService are GET type. By using the abstract class NetworkBoundResource to load each object by overriding createCall() in its Repository, like UserRepository#loadUser(String login).

In Post, I update data remotely on server which I might have instance of it locally with Room, What/How to update Room depending on the API? Is the same class, NetworkBoundResource, is applicable with POST requests? What is the best scenario in this case?

Thanks!

SergeiVasilenko commented 7 years ago

NetworkBoundResources is not applicable with POST request for me. I created similar class with follow difference:

@MainThread
ChangeAction(AppExecutors appExecutors) {
    mAppExecutors = appExecutors;
    makeChange();
}

private void makeChange() {
    LiveData<ApiResponse<RequestType>> apiResponse = createCall();
    apiResponse.observeForever(response -> {
        if (response.isSuccessful()) {
            mAppExecutors.diskIO().execute(() -> {
                saveCallResult(processResponse(response));
                mAppExecutors.mainThread().execute(() -> {
                    mResult.addSource(loadFromDb(), newData -> mResult.setValue(Resource.success(newData)));
                });
            });
        } else {
            onChangeFailed();
            mResult.addSource(loadFromDb(), newData -> mResult.setValue(Resource.error(response.error, newData)));
        }
    });
}

Be careful! I didn't test this code, and it may have bugs.

amrro commented 7 years ago

I suggest to override saveCallResult(@NonNull RequestType item) instead of adding more code. So, every Call in any repository handle its case.

beylmk commented 5 years ago

@amrro could you elaborate on your response or provide an example?

plabon commented 4 years ago

What is the solution to this post request problem? Is there any google recommendation?

dlam commented 4 years ago

@plabon Similar to GithubService linked earlier, OkHttp/Retrofit also provides an @POST annotation.

plabon commented 4 years ago

@dlam No i was asking about using NetworkBoundResources How can I put data in local database and post the data to server?