I'm trying load posts from blog. I use mosby + retrofit + rxjava.
public class PostRepository implements IPostRepository {
private Api api;
private long last_id = 0;
private Single<List<Post>> postList;
public PostRepository(Api api) {
this.api = api;
}
#Override
public Single<List<Post>> getList() {
this.load();
return postList;
}
private void load() {
Single<List<Post>> tmp;
Log.d(Configuration.DEBUG_TAG, "Loading " + last_id);
tmp = api.getPostList(last_id)
.map(posts -> {
ArrayList<Post> postList = new ArrayList<>();
for (PostResponse post : posts) {
if (last_id == 0 || last_id > post.id) {
last_id = post.id;
}
postList.add(new Post(
post.id,
post.thumb,
post.created_at,
post.title
));
}
return postList;
});
if (postList == null) {
postList = tmp;
} else {
postList.mergeWith(tmp);
}
}
#Override
public Single<Post> getDetail(long id) {
return api.getPost(id)
.map(postResponse -> new Post(
postResponse.id,
postResponse.thumb,
postResponse.created_at,
postResponse.title,
postResponse.body
));
}
}
and api
public interface Api {
#GET("posts")
Single<PostListResponse> getPostList(#Query("last_id") long last_id);
#GET("post/{id}")
Single<PostResponse> getPost(#Path("id") long id);
}
First query to website is ok. https://site/posts?last_id=0
But second run function getList does not work.
I always get the same get query with last_id = 0, but line in console write
D/App: Loading 1416
D/App: 1416
D/OkHttp: --> GET https://site/posts?last_id=0 http/1.1
if i write
tmp = api.getPostList(1000)
then i get true query string https://site/posts?last_id=1000
Update
I rewrite code repository.
public class PostRepository implements IPostRepository {
private Api api;
private long last_id = 0;
private List<Post> postList = new ArrayList<>();
private Observable<List<Post>> o;
public PostRepository(Api api) {
this.api = api;
}
#Override
public Single<List<Post>> getList() {
return load();
}
private Single<List<Post>> load() {
return api.getPostList(last_id)
.map(posts -> {
for (PostResponse post : posts) {
if (last_id == 0 || last_id > post.id) {
last_id = post.id;
}
postList.add(new Post(
post.id,
post.thumb,
post.created_at,
post.title
));
}
return postList;
});
}
#Override
public Single<Post> getDetail(long id) {
return api.getPost(id)
.map(postResponse -> new Post(
postResponse.id,
postResponse.thumb,
postResponse.created_at,
postResponse.title,
postResponse.body
));
}
}
It's work
Your problem lies in this code fragment:
if (postList == null) {
postList = tmp;
} else {
postList.mergeWith(tmp); // here
}
Operators on observables are performing immutable operations, which means that it always returns new stream which is a modified version of the previous one. That means, that when you apply mergeWith operator, the result of this is thrown away as you are not storing it anywhere. The most easy to fix this is to replace the old postList variable with the new stream.
However, this is not optimal way of doing this. You should have a look on Subjects and emit new values within the old stream as your current solution will not affect previous subscribers as they have subscribed to a different stream
Related
I have a function that takes an article id list to set on the adapter. Everything works fine until at least one of the requests fails. Then the returned list is empty. How to make it ignore a failing request and move on to the next one? For example, I request 5 articles 1 fail, 4 are okay, so I get a list of 4.
I know, I need to use onErrorResumeNext() here, but I don't know-how.
Interface:
#GET("articles/{id}")
Observable<Articles> getArticle1(#Path("id") int id);
Activity:
private void getMoreArticles(List<Integer> l) {
ApiInterface apiInterface = ApiClient.getApiClientRX().create(ApiInterface.class);
List<Observable<?>> requests = new ArrayList<>();
for (int id : l) {
requests.add(apiInterface.getArticle1(id));
}
Observable.zip(requests, new Function<Object[], List<Articles>>() {
#Override
public List<Articles> apply(#NonNull Object[] objects) {
List<Articles> articlesArrayList = new ArrayList<>();
for (Object response : objects) {
articlesArrayList.add((Articles) response);
}
return articlesArrayList;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(Observable.<List<Articles>>empty())
.subscribe(
new Consumer<List<Articles>>() {
#Override
public void accept(List<Articles> articlesList) {
adapter = new Adapter(articlesList, MainActivity.this);
if (fav) recyclerView.setAdapter(adapter);
else addRV().setAdapter(adapter);
adapter.notifyDataSetChanged();
initListener();
swipeRefreshLayout.setRefreshing(false);
}
},
new Consumer<Throwable>() {
#Override
public void accept(Throwable e) throws Exception {
}
}
).isDisposed();
}
I tried to simplify your use case a bit but I hope you got my point. You need to somehow "signal" that there was some problem in your API call and this specific Articles object should be skipped in your .zip() operator's zipper function. You can for example wrap the return value into Optional. When the value is preset, it indicates everything went fine. If not, the API call failed.
class SO69737581 {
private Observable<Articles> getArticle1(int id) {
return Observable.just(new Articles(id))
.map(articles -> {
if (articles.id == 2) { // 1.
throw new RuntimeException("Invalid id");
} else {
return articles;
}
});
}
Observable<List<Articles>> getMoreArticles(List<Integer> ids) {
List<Observable<Optional<Articles>>> requests = new ArrayList<>();
for (int id : ids) {
Observable<Optional<Articles>> articleRequest = getArticle1(id)
.map(article -> Optional.of(article)) // 2.
.onErrorReturnItem(Optional.empty()); // 3.
requests.add(articleRequest);
}
return Observable.zip(requests, objects -> {
List<Articles> articlesArrayList = new ArrayList<>();
for (Object response : objects) {
Optional<Articles> optionalArticles = (Optional<Articles>) response;
optionalArticles.ifPresent(articlesArrayList::add); // 4.
}
return articlesArrayList;
});
}
}
Explanation of interesting parts:
Simulate API error with id = 2
Wrap result of API the call into optional
Return empty optional when an error occurs
Add articles value into result array if the value is present
Verification:
public class SO69737581Test {
#Test
public void failedArticleCallsShouldBeSkipped() {
SO69737581 tested = new SO69737581();
TestObserver<List<Articles>> testSubscriber = tested
.getMoreArticles(Arrays.asList(1, 2, 3, 4))
.test();
List<Articles> result = Arrays.asList(
new Articles(1),
new Articles(3),
new Articles(4)
);
testSubscriber.assertComplete();
testSubscriber.assertValue(result);
}
}
For sake of completeness, this is how I defined Article class:
class Articles {
public int id;
public Articles(int id) {
this.id = id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Articles articles = (Articles) o;
return id == articles.id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
}
i have a fragment in my app that i show two list of saparate data in it.i'm using from android architecture components to load my data.
Once the data is fetched from the network, I store it locally using Room DB and then display it on the UI using ViewModel that observes on the LiveData object (this works fine). However, I want to be able to have a refreshLayout which When Refreshing Occurs a refresh action and perform a network request to get new data from the API if and only if there is a network connection.The issue is when Refreshing Occurs data load from locate database and network together .
my question is :How do I manage to get data only from Network when refreshing data?
How do I manage to get data only from Network when refreshing data?
I've seen this question and it didn't help me...
my codes:
repository:
public NetworkResult<LiveData<HomeHealthModel>> getHomeHealth(String query) {
MutableLiveData<String> _liveError = new MutableLiveData<>();
MutableLiveData<HomeHealthModel> data = new MutableLiveData<>();
LiveData<List<GeneralItemModel>> liveClinics = App.getDatabase().getGeneralItemDAO().getTops(GeneralItemType.Clinics, GeneralItemType.TOP);
LiveData<List<GeneralItemModel>> liveDoctors = App.getDatabase().getGeneralItemDAO().getTops(GeneralItemType.Doctors, GeneralItemType.TOP);
setupService(_liveError); //request data from network
data.postValue(new HomeHealthModel(liveClinics, liveDoctors));
_liveError.postValue(String.valueOf(NetworkResponseType.LocaleData));
return new NetworkResult<>(_liveError, data);
}
my viewModel
public class HomeHealthVM extends ViewModel {
private MutableLiveData<String> queryLiveData;
private LiveData<String> networkErrors;
private LiveData<List<GeneralItemModel>> Clinics;
private LiveData<List<GeneralItemModel>> Doctors;
public HomeHealthVM(HealthRepository repository) {
queryLiveData = new MutableLiveData<>();
LiveData<NetworkResult<LiveData<HomeHealthModel>>> repoResult;
repoResult = Transformations.map(queryLiveData, repository::getHomeHealth);
LiveData<HomeHealthModel> model = Transformations.switchMap(repoResult, input -> input.data);
Doctors = Transformations.switchMap(model, HomeHealthModel::getDoctors);
Clinics = Transformations.switchMap(model, HomeHealthModel::getClinics);
networkErrors = Transformations.switchMap(repoResult, input -> input.error);
}
public void search(String queryString) {
queryLiveData.postValue(queryString);
}
public String lastQueryValue() {
return queryLiveData.getValue();
}
public LiveData<String> getNetworkErrors() {
return networkErrors;
}
public LiveData<List<GeneralItemModel>> getClinics() {
return Clinics;
}
public LiveData<List<GeneralItemModel>> getDoctors() {
return Doctors;
}
}
my fragment code:
private void setupViewModel() {
ViewModelFactory<HealthRepository> factory = new ViewModelFactory<>(new HealthRepository());
healthVM = ViewModelProviders.of(this, factory).get(HomeHealthVM.class);
healthVM.getNetworkErrors().observe(this, states -> {
try {
if (Integer.parseInt(states) != WarningDialogType.Success &&
Integer.parseInt(states) != WarningDialogType.Locale) {
stopLoading();
linerNoInternet.setVisibility(View.VISIBLE);
linerContent.setVisibility(View.GONE);
}
} catch (Exception e) {
stopLoading();
linerNoInternet.setVisibility(View.VISIBLE);
linerContent.setVisibility(View.GONE);
}
});
healthVM.getDoctors().observe(this, doctors -> {
if (doctors.size() > 0) {
doctorsAdapter.submitList(doctors);
stopLoading();
} else {
}
});
healthVM.getClinics().observe(this, clinics -> {
if (clinics.size() > 0) {
clinicsAdapter.submitList(clinics);
stopLoading();
} else {
conesClinics.setVisibility(View.GONE);
}
});
healthVM.search("");
}
I am attempting to developed an Android application based on the following talk presented by Jake Wharton
The State of Managing State with RxJava
21 March 2017 – Devoxx (San Jose, CA, USA)
Jake promised a part 2 and/or GITHUB example which I am unable to find (If indeed either exists)
At a high level I can follow/understand the majority of the above talk.
However I have the following questions.
I can see how employing UiEvent, UiModel, Action, and Result keeps concerns separated.
What I am confused about is the following:-
The diagram on slide 194 shows the "flow/stream" of Observables as
Android Device -----> Observable<UiEvent> -----> <application code> -----> Observable<Action> -----> {Backend}
{Backend} -----> Observable<Result> -----> <application code> -----> Observable<UiModel> -----> Android Device
Slide 210 contains this code snippet, showing how the Result(s) stream is "scan"ned into UiModel
SubmitUiModel initialState = SubmitUiModel.idle();
Observable<Result> results = /* ... */;
Observable<SubmitUiModel> uiModels = results.scan(initialState, (state, result) -> {
if (result == CheckNameResult.IN_FLIGHT
|| result == SubmitResult.IN_FLIGHT)
return SubmitUiModel.inProgress();
if (result == CheckNameResult.SUCCESS)
return SubmitUiModel.idle();
if (result == SubmitResult.SUCCESS)
return SubmitUiModel.success();
// TODO handle check name and submit failures...
throw new IllegalArgumentException("Unknown result: " + result);
});
and the final code snippet on slide 215, the code snippet resembles this:-
ObservableTransformer<SubmitAction, SubmitResult> submit =
actions -> actions.flatMap(action -> service.setName(action.name)
.map(response -> SubmitResult.SUCCESS)
.onErrorReturn(t -> SubmitResult.failure(t.getMessage()))
.observeOn(AndroidSchedulers.mainThread())
.startWith(SubmitResult.IN_FLIGHT));
ObservableTransformer<CheckNameAction, CheckNameResult> checkName =
actions -> actions.switchMap(action -> action
.delay(200, MILLISECONDS, AndroidSchedulers.mainThread())
.flatMap(action -> service.checkName(action.name))
.map(response -> CheckNameResult.SUCCESS)
.onErrorReturn(t -> CheckNameResult.failure(t.getMessage()))
.observeOn(AndroidSchedulers.mainThread())
.startWith(CheckNameResult.IN_FLIGHT));
which illustrates conversion from Action(s) to Result(s)
what am I missing from this talk/slide-deck on how to combine the UiEvent/UiModel to the Action/Result stream?
The stream is driven by UiEvents
How do you complete the flow from UiEvent(s) to Action back to Result then finally UiModel?
UPDATE
Using the Star Wars API I have taken the following approach
I use my UI Events to drive the transformation between UI Events to Results via Actions, then scan the results to map back to UI Model.
Heres my classes and code:-
ACTION CLASSES
==============
public abstract class Action<T> {
Api service = Service.instance();
final T data;
public Action(final T data) {
this.data = data;
}
public T getData() {
return data;
}
public abstract Observable<Response<String>> execute();
}
public class CheckCharacterAction extends Action<String> {
public CheckCharacterAction(final String characterName) {
super(characterName);
}
#Override
public Observable<Response<String>> execute() {
return service.peopleSearch(getData());
}
}
public class CheckFilmAction extends Action<String> {
public CheckFilmAction(final String filmTitle) {
super(filmTitle);
}
#Override
public Observable<Response<String>> execute() {
return service.filmSearch(getData());
}
}
public class SearchAction extends Action<String> {
public SearchAction(final String search) {
super(search);
}
#Override
public Observable<Response<String>> execute() {
return service.filmSearch(getData());
}
}
EVENT CLASSES
=============
public abstract class UiEvent<T> {
private final T data;
public UiEvent(final T data) {
this.data = data;
}
public T getData() {
return data;
}
}
public class CharacterUiEvent extends UiEvent<String> {
public CharacterUiEvent(final String name) {
super(name);
}
}
public class FilmUiEvent extends UiEvent<String> {
public FilmUiEvent(final String title) {
super(title);
}
}
public class SearchUiEvent extends UiEvent<String> {
public SearchUiEvent(final String data) {
super(data);
}
}
UI MODEL CLASSES
================
public class UiModel<T> {
public final boolean isProgress;
public final String message;
public final boolean isSuccess;
public T data;
public UiModel(final boolean isProgress) {
this.isProgress = isProgress;
this.message = null;
this.isSuccess = false;
this.data = null;
}
public UiModel(final T data) {
this.isProgress = false;
this.message = null;
this.isSuccess = true;
this.data = data;
}
public UiModel(final String message) {
this.isProgress = false;
this.message = message;
this.isSuccess = false;
this.data = null;
}
public UiModel(final boolean isProgress, final String message, final boolean isSuccess, final T data) {
this.isProgress = isProgress;
this.message = message;
this.isSuccess = isSuccess;
this.data = data;
}
}
public class CharacterUiModel extends UiModel<JsonData> {
public CharacterUiModel(final boolean isProgress) {
super(isProgress);
}
public CharacterUiModel(final JsonData data) {
super(data);
}
public CharacterUiModel(final String message) {
super(message);
}
public CharacterUiModel(final boolean isProgress, final String message, final boolean isSuccess, final JsonData data) {
super(isProgress, message, isSuccess, data);
}
public static CharacterUiModel inProgress() {
return new CharacterUiModel(true);
}
public static CharacterUiModel success(final JsonData data) {
return new CharacterUiModel(data);
}
public static CharacterUiModel failure(final String message) {
return new CharacterUiModel(message);
}
}
public class FilmUiModel extends UiModel<JsonData> {
public FilmUiModel(final boolean isProgress) {
super(isProgress);
}
public FilmUiModel(final JsonData data) {
super(data);
}
public FilmUiModel(final String message) {
super(message);
}
public FilmUiModel(final boolean isProgress, final String message, final boolean isSuccess, final JsonData data) {
super(isProgress, message, isSuccess, data);
}
public static FilmUiModel inProgress() {
return new FilmUiModel(true);
}
public static FilmUiModel success(final JsonData data) {
return new FilmUiModel(data);
}
public static FilmUiModel failure(final String message) {
return new FilmUiModel(message);
}
}
public class SearchUiModel extends UiModel<JsonData> {
private SearchUiModel(final boolean isProgress) {
super(isProgress);
}
private SearchUiModel(final JsonData data) {
super(data);
}
private SearchUiModel(final String message) {
super(message);
}
private SearchUiModel(final boolean isProgress, final String message, final boolean isSuccess, final JsonData data) {
super(isProgress, message, isSuccess, data);
}
public static SearchUiModel idle() {
return new SearchUiModel(false, null, false, null);
}
public static SearchUiModel inProgress() {
return new SearchUiModel(true);
}
public static SearchUiModel success(final JsonData data) {
return new SearchUiModel(data);
}
public static SearchUiModel failure(final String message) {
return new SearchUiModel(message);
}
}
RESULT CLASSES
==============
public abstract class Result<T> {
public enum LIFECYCLE {
DEPARTURE_LOUNGE,
IN_FLIGHT,
LANDED_SAFELY,
CRASHED_BURNED
}
final LIFECYCLE lifecycle;
final T data;
final String errorMessage;
public Result(final LIFECYCLE lifecycle, final T data, final String errorMessage) {
this.lifecycle = lifecycle;
this.data = data;
this.errorMessage = errorMessage;
}
public T getData() {
return data;
}
public String getErrorMessage() {
return errorMessage;
}
public LIFECYCLE getLifecycle() {
return lifecycle;
}
}
public class CharacterResult extends Result<JsonData> {
private CharacterResult(final LIFECYCLE lifecycle, final JsonData data, final String errorMessage) {
super(lifecycle, data, errorMessage);
}
private CharacterResult(final LIFECYCLE lifecycle) {
super(lifecycle, null, null);
}
public static CharacterResult departureLounge() {
return new CharacterResult(LIFECYCLE.DEPARTURE_LOUNGE);
}
public static CharacterResult inflight() {
return new CharacterResult(LIFECYCLE.IN_FLIGHT);
}
public static CharacterResult landedSafely(final JsonData data) {
return new CharacterResult(LIFECYCLE.LANDED_SAFELY, data, null);
}
public static CharacterResult crashedBurned(final String errorMessage) {
return new CharacterResult(LIFECYCLE.CRASHED_BURNED, null, errorMessage);
}
}
public class FilmResult extends Result<JsonData> {
private FilmResult(final LIFECYCLE lifecycle, final JsonData data, final String errorMessage) {
super(lifecycle, data, errorMessage);
}
private FilmResult(final LIFECYCLE lifecycle) {
super(lifecycle, null, null);
}
public static FilmResult departureLounge() {
return new FilmResult(LIFECYCLE.DEPARTURE_LOUNGE);
}
public static FilmResult inflight() {
return new FilmResult(LIFECYCLE.IN_FLIGHT);
}
public static FilmResult landedSafely(final JsonData data) {
return new FilmResult(LIFECYCLE.LANDED_SAFELY, data, null);
}
public static FilmResult crashedBurned(final String errorMessage) {
return new FilmResult(LIFECYCLE.CRASHED_BURNED, null, errorMessage);
}
}
public class SearchResult extends Result<JsonData> {
private SearchResult(final LIFECYCLE lifecycle, final JsonData data, final String errorMessage) {
super(lifecycle, data, errorMessage);
}
private SearchResult(final LIFECYCLE lifecycle) {
super(lifecycle, null, null);
}
public static SearchResult departureLounge() {
return new SearchResult(LIFECYCLE.DEPARTURE_LOUNGE);
}
public static SearchResult inflight() {
return new SearchResult(LIFECYCLE.IN_FLIGHT);
}
public static SearchResult landedSafely(final JsonData data) {
return new SearchResult(LIFECYCLE.LANDED_SAFELY, data, null);
}
public static SearchResult crashedBurned(final String errorMessage) {
return new SearchResult(LIFECYCLE.CRASHED_BURNED, null, errorMessage);
}
}
I then set up my Rx Streams as follows from my Activity onCreate() method:-
final Observable<SearchUiEvent> searchEvents = RxView.clicks(activityMainBinding.searchButton)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.map(ignored -> new SearchUiEvent(activityMainBinding.filmTitle.getText().toString()));
final Observable<FilmUiEvent> filmEvents = RxTextView.afterTextChangeEvents(activityMainBinding.filmTitle)
.skipInitialValue()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.delay(1000, MILLISECONDS, AndroidSchedulers.mainThread())
.map(text -> new FilmUiEvent(text.view().getText().toString()));
final Observable<CharacterUiEvent> characterEvents = RxTextView.afterTextChangeEvents(activityMainBinding.people)
.skipInitialValue()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.delay(200, MILLISECONDS, AndroidSchedulers.mainThread())
.map(text -> new CharacterUiEvent(text.view().getText().toString()));
/**
*
*/
final Observable<UiEvent> uiEvents = Observable.merge(searchEvents, filmEvents, characterEvents);
/*********
*
*/
final ObservableTransformer<SearchUiEvent, SearchResult> searchAction =
events -> events.flatMap(event -> new SearchAction(event.getData()).execute().subscribeOn(Schedulers.io()))
.map(response -> SearchResult.landedSafely(new JsonData(response.body())))
.onErrorReturn(throwable -> SearchResult.crashedBurned(throwable.getMessage()))
.startWith(SearchResult.inflight());
final ObservableTransformer<FilmUiEvent, FilmResult> filmAction =
events -> events.flatMap(event -> new CheckFilmAction(event.getData()).execute().subscribeOn(Schedulers.io()))
.map(response -> FilmResult.landedSafely(new JsonData(response.body())))
.onErrorReturn(throwable -> FilmResult.crashedBurned(throwable.getMessage()))
.startWith(FilmResult.inflight());
final ObservableTransformer<CharacterUiEvent, CharacterResult> characterAction =
events -> events.flatMap(event -> new CheckCharacterAction(event.getData()).execute().subscribeOn(Schedulers.io()))
.map(response -> CharacterResult.landedSafely(new JsonData(response.body())))
.onErrorReturn(throwable -> CharacterResult.crashedBurned(throwable.getMessage()))
.startWith(CharacterResult.inflight());
final ObservableTransformer<UiEvent, ? extends Result> whatever = events -> events.publish(shared -> Observable.merge(
shared.ofType(SearchUiEvent.class).compose(searchAction),
shared.ofType(CharacterUiEvent.class).compose(characterAction),
shared.ofType(FilmUiEvent.class).compose(filmAction)));
/**
*
*/
final UiModel initialState = SearchUiModel.idle();
final Observable<? extends Result> results = uiEvents.compose(whatever).doOnSubscribe(COMPOSITE_DISPOSABLE::add);
final Observable<UiModel> models = results.scan(initialState, (state, result) -> {
Log.e(TAG, "scan() state = " + state + " result = " + result);
if (result.getLifecycle().equals(SearchResult.LIFECYCLE.DEPARTURE_LOUNGE) ||
result.getLifecycle().equals(CharacterResult.LIFECYCLE.DEPARTURE_LOUNGE) ||
result.getLifecycle().equals(FilmResult.LIFECYCLE.DEPARTURE_LOUNGE)) {
return SearchUiModel.idle();
}
if (result.getLifecycle().equals(SearchResult.LIFECYCLE.IN_FLIGHT) ||
result.getLifecycle().equals(CharacterResult.LIFECYCLE.IN_FLIGHT) ||
result.getLifecycle().equals(FilmResult.LIFECYCLE.IN_FLIGHT)) {
return SearchUiModel.inProgress();
}
if (result.getLifecycle().equals(SearchResult.LIFECYCLE.LANDED_SAFELY) ||
result.getLifecycle().equals(CharacterResult.LIFECYCLE.LANDED_SAFELY) ||
result.getLifecycle().equals(FilmResult.LIFECYCLE.LANDED_SAFELY)) {
return SearchUiModel.success((JsonData) result.getData());
}
if (result.getLifecycle().equals(SearchResult.LIFECYCLE.CRASHED_BURNED) ||
result.getLifecycle().equals(CharacterResult.LIFECYCLE.CRASHED_BURNED) ||
result.getLifecycle().equals(FilmResult.LIFECYCLE.CRASHED_BURNED)) {
return SearchUiModel.failure(result.getErrorMessage());
}
return null;
});
models.doOnSubscribe(COMPOSITE_DISPOSABLE::add).subscribe(model -> report(model), throwable -> error(throwable));
As soon as my activity displays I get the following logs:-
2018-10-09 14:22:33.310 D/MainActivity: report() called with: model = [UiModel{isProgress=false, message='null', isSuccess=false, data=null}]
2018-10-09 14:22:33.311 E/MainActivity: scan() state = UiModel{isProgress=false, message='null', isSuccess=false, data=null} result = SearchResult{lifecycle=IN_FLIGHT, data=null, errorMessage='null'}
2018-10-09 14:22:33.311 D/MainActivity: report() called with: model = [UiModel{isProgress=true, message='null', isSuccess=false, data=null}]
2018-10-09 14:22:33.313 E/MainActivity: scan() state = UiModel{isProgress=true, message='null', isSuccess=false, data=null} result = CharacterResult{lifecycle=IN_FLIGHT, data=null, errorMessage='null'}
2018-10-09 14:22:33.313 D/MainActivity: report() called with: model = [UiModel{isProgress=true, message='null', isSuccess=false, data=null}]
2018-10-09 14:22:33.313 E/MainActivity: scan() state = UiModel{isProgress=true, message='null', isSuccess=false, data=null} result = FilmResult{lifecycle=IN_FLIGHT, data=null, errorMessage='null'}
2018-10-09 14:22:33.313 D/MainActivity: report() called with: model = [UiModel{isProgress=true, message='null', isSuccess=false, data=null}]
Im guessing I get these IN FLIGHT results due to my .startWith() statements.
When I either click my Search button or enter any text in my EditText views I see the following logs:-
2018-10-09 14:55:19.463 E/MainActivity: scan() state = UiModel{isProgress=false, message='null', isSuccess=true, data=com.test.model.JsonData#5e0b6f1} result = FilmResult{lifecycle=LANDED_SAFELY, data=com.test.model.JsonData#8ae4d86, errorMessage='null'}
2018-10-09 14:55:19.463 D/MainActivity: report() called with: model = [UiModel{isProgress=false, message='null', isSuccess=true, data=com.test.model.JsonData#8ae4d86}]
Why do I not see "IN FLIGHT" then "LANDED SAFELY"?
I only get "LANDED SAFELY"
Is my approach to transforming between UI Event -> Action -> Result -> UI Model anywhere close to what is described by Mr J Wharton?
Where have I gone wrong?
UPDATE (II)
My mistake was to not include all my downstream Rx within the .flatmap() operation.
CLARIFICATION
Does this pattern of UI Event ---> Action ---> Result ---> UI Model still apply for cases where there is no "Backend" as such? e.g. a Home screen could present the user with a number of options (buttons) to navigate to lower level screens within the application. The UI Event would be "Button Click" the UI Model would return with the associated Activity class to employ with the startActivity() method call.
How can I amalgamate the UI input events of a login screen into a single stream of UI events where I have two EditText fields (User Name and Password) and a Login Button.
I would want the button click UI event to contain the user name and user password entered. If I was using RxBinding to process the EditTexts and the Login button click I cannot see how I can combine these three Observables into my UI event stream and have the EditTexts validated to ensure they have data entered and then pass this user entered data to my back end login API (or maybe Google Sign In for example)
(I was adding a comment but it was too long)
I cannot help with the talks and so on presented by Jake. But regarding your last question:
Does this pattern of UI Event ---> Action ---> Result ---> UI Model
still apply for cases where there is no "Backend" as such?
It does, it is just that the backend is your application state repository.
In this kind of architecture there should only be one place of truth for your application: be it a backend, a local database, a combination of both or whatever solution is appropriate for your usecase.
Having that in mind your Action streams should modify the state either by doing calls to the backend, posting changes to a database or writing elements in the sharedSetting. Similarly, changes in your state should trigger sending Results down your streams.
The specific details would depend on what you use as a source of truth for your application.
DataFlow and State
It uses mainly Paco and Jake Wharton RxState idea plus added some more stuff.
To use UiEvent → Action, Result → UiModel transformers and always act
on a single state with the help of RxJava operators (Forming a single
stream of events, then based on their types handling actions with
different transformers, then combine results again, modifying the
state and then finally render it on the UI.
or not to use transformers and make it a little bit “simpler”.
So here is the “full” view model code without using any transformers:
class SomeViewModel(private val someRepository: SomeRepository): ViewModel() {
val uiEvents: PublishSubject<UiEvent> = PublishSubject.create()
val outputState: MutableLiveData<Result<UiState>> = MutableLiveData()
init {
uiEvents.subscribe {
when (it) {
is FirstEvent -> getSomeResultsFromRepo(it.id)
is SecondEvent -> handleSecondEvent()
}
}
}
fun getSomeResultsFromRepo(id: String) {
someRepository.getResult(id)
.map { UiState(it) }
.map { Result.success(it) }
.startWith(Result.loading())
.onErrorReturn { handleError(it) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
outputState.postValue(it)
})
}
fun handleSecondEvent() {
/* do something here */
someRepository.getSomeOtherResult()
.map { UiState(it) }
.map { Result.success(it) }
.startWith(Result.loading())
.onErrorReturn { handleError(it) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
outputState.postValue(it)
})
}
private fun handleError(error: Throwable): Result<UiState> {
return if (error is RetrofitException) {
when (error.kind) {
RetrofitException.Kind.NETWORK -> Result.failure(NetworkError(error))
RetrofitException.Kind.HTTP -> Result.failure(ServerError(error))
RetrofitException.Kind.UNEXPECTED -> Result.failure(UnknownError(error))
else -> Result.failure(UnknownError(error))
}
} else {
Result.failure(UnknownError(error))
}
}
class Factory #Inject constructor(private val someRepo: SomeRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
#Suppress("UNCHECKED_CAST")
return SomeViewModel(someRepo) as T
}
}
}
As you can see here 2 streams: a uiEvents (1st stream) which gets all the input events from the UI. As long as the UI exists it will be catching those events. Based on the event types it calls some repository functions (use cases) that are returning some response and then they are updating the model (2nd stream) with one of the possible outcomes: Success, Error or Loading.
Also transform the errors in API to so called RetrofitErrors, and based on their type it can show different error messages to the User.
There is some duplication as well that can be avoided easily, but what I wanted to show here is that it always start with a Loading result, then either a Success or an Error.
One of the most important thing is that this way "To keep state in the stream, which is a LiveData."
One benefit of this setup (just like using a BehaviourSubject) is that it will always return the last state — on orientation change it is very useful as it just loads the last available state.
Also it is highly testable as each piece can be tested in separation with providing mocked repo or view and it is also very easy to debug as we always have a current state in the stream.
I have successfully implemented a PagedList.BoundaryCallback, which loads a list of upcoming movies from "themoviedb" database, and saves the response into the database.
But it does not work the way I want it. Since the request return a list of upcoming movies, the response changes frequently. But if I already have data in my database, the onZeroItemsLoaded() method is not called.
My question is, how can I force the data source, or this boundary callback to always make an api request, and refresh the content of my database from the network?
public class UpcomingMoviesBoundaryCallback extends PagedList.BoundaryCallback<MovieListItemEntity> {
public static final String TAG = UpcomingMoviesBoundaryCallback.class.getSimpleName();
private UpcomingMoviesRepository upcomingMoviesRepository;
private int page = 1;
public UpcomingMoviesBoundaryCallback(UpcomingMoviesRepository upcomingMoviesRepository) {
this.upcomingMoviesRepository = upcomingMoviesRepository;
}
#Override
public void onZeroItemsLoaded() {
super.onZeroItemsLoaded();
Log.d(TAG, "onZeroItemsLoaded: ");
load();
}
#Override
public void onItemAtEndLoaded(#NonNull MovieListItemEntity itemAtEnd) {
super.onItemAtEndLoaded(itemAtEnd);
Log.d(TAG, "onItemAtEndLoaded: ");
load();
}
#SuppressLint("CheckResult")
private void load() {
upcomingMoviesRepository.getUpcoming(page)
.doOnSuccess(result -> {
upcomingMoviesRepository.saveUpcomingMovies(result);
page = result.getPage() + 1;
})
.subscribeOn(Schedulers.io())
.subscribe(result -> {
Log.d(TAG, "load: " + result);
}, error -> {
Log.d(TAG, "load: error", error);
});
}
}
public class UpcomingMoviesRepositoryImpl implements UpcomingMoviesRepository {
private static final String TAG = UpcomingMoviesRepository.class.getSimpleName();
private MovieResponseMapper movieResponseMapper = new MovieResponseMapper();
private MovieAppApi mMovieAppApi;
private UpcomingDao mUpcomingDao;
public UpcomingMoviesRepositoryImpl(MovieAppApi mMovieAppApi, UpcomingDao mUpcomingDao) {
this.mMovieAppApi = mMovieAppApi;
this.mUpcomingDao = mUpcomingDao;
}
#Override
public Single<MovieListResponse> getUpcoming(int page) {
return mMovieAppApi.upcoming(page);
}
#Override
public Single<MovieListResponse> getUpcoming() {
return mMovieAppApi.upcoming();
}
#Override
public void saveUpcomingMovies(MovieListResponse movieListResponse) {
Executors.newSingleThreadExecutor().execute(() -> {
long[] inseted = mUpcomingDao.save(movieResponseMapper.map2(movieListResponse.getResults()));
Log.d(TAG, "saveUpcomingMovies: " + inseted.length);
});
}
#Override
public LiveData<PagedList<MovieListItemEntity>> getUpcomingLiveData() {
PagedList.Config config = new PagedList.Config.Builder()
.setEnablePlaceholders(true)
.setPageSize(12)
.build();
DataSource.Factory<Integer, MovieListItemEntity> dataSource = mUpcomingDao.upcoming();
LivePagedListBuilder builder =
new LivePagedListBuilder(dataSource, config)
.setBoundaryCallback(new UpcomingMoviesBoundaryCallback(this));
return builder.build();
}
}
Inside the repository you can query database to check if data is old then you can start an async network call that will write the result directly to the database. Because the database is being observed, the UI bound to the LiveData<PagedList> will update automatically to account for the new dataset.
#Override
public LiveData<PagedList<MovieListItemEntity>> getUpcomingLiveData() {
if(mUpcomingDao.isDatasetValid()) //Check last update time or creation date and invalidate data if needed
upcomingMoviesRepository.getUpcoming()
.doOnSuccess(result -> {
upcomingMoviesRepository.clearUpcomingMovies()
upcomingMoviesRepository.saveUpcomingMovies(result);
})
.subscribeOn(Schedulers.io())
.subscribe(result -> {
Log.d(TAG, "load: " + result);
}, error -> {
Log.d(TAG, "load: error", error);
});
}
I need to a simple example for use GraphQl in android .
How can I use from GraphQl in android (tutorial).
In order to use GraphQL (in general), you need two things:
1. A GraphQL server
There are a few ways how you could go about this. Of course, you could simply go and implement one yourself in any server-side language you like.
Other (faster) approaches are to take advantage of existing tooling and generate a GraphQL API using services like graphql-up or create-graphql-server or even services like Graphcool (disclaimer: I work for them).
2. A GraphQL client library
Though this one isn't strictly necessary and you could also simply interact with the GraphQL server through plain HTTP (sending your queries and mutations in the body of POST requests), it is certainly beneficial to use existing tools that take repetitive work like caching or UI integrations off your shoulders. One of the most popular GraphQL clients right now is Apollo, and they're very actively working on a version for Android as well. However, this hasn't been officially released yet. So, you either have to use their existing development version of chose the former approach using plain HTTP for now.
Here is an example of querying GraphQl from Client. In this example I am using Retrofit 2:
// QueryHelper.java
// This line below is the simple format of Gql query
query = "query{me{name, location, majorOfInterest,profilePhoto{url(size: 400) }}}";
//Post the query using Retrofit2
GqlRetrofitClient.getInstance(getContext()).fetchUserDetails(new GqlQueryRequest(queryUserDetails)).enqueue(new Callback<UserDetails>() {
#Override
public void onResponse(Call<UserDetails> call, Response<UserDetails> response) {
//OnResponse do something();
}
#Override
public void onFailure(Call<UserDetails> call, Throwable t) {
Log.d(TAG, "Failed to fetch User details");
}
});
//GqlClient.java
public class GqlRetrofitClient {
public static final String BASE_URL = BuildConfig.DOMAIN;
private static GqlRetrofitClient sInstance;
private GqlRetrofitService mGqlRetrofitService;
Gson gson = new GsonBuilder().create();
private GqlRetrofitClient(final Context context) {
// Network Interceptor for logging
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("X-User-Token", "AUTH_TOKEN")
.addHeader("X-User_Email", "Email")
.addHeader("content-type", "application/json")
.build();
return chain.proceed(request);
}
})
.addInterceptor(httpLoggingInterceptor)
.build();
// Retrofit initialization
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.build();
mGqlRetrofitService = retrofit.create(GqlRetrofitService.class);
}
// Create an instance of GqlRetrofitClient to create retrofit service
public static GqlRetrofitClient getInstance(Context context){
if(sInstance == null){
sInstance = new GqlRetrofitClient(context.getApplicationContext());
}
return sInstance;
}
// Method call to get User details
public Call<UserDetails> fetchUserDetails(GqlQueryRequest queryUserDetails){
return mGqlRetrofitService.getUserDetails(queryUserDetails);
}
}
//GqlRetrofitService.java
public interface GqlRetrofitService{
#POST("/api/graph.json")
Call<UserDetails> getUserDetails(#Body GqlQueryRequest body);
}
In your manifest to add
<uses-permission android:name="android.permission.INTERNET"/>
Your dependencies
// Kotlin Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4'
//OkHttp
implementation ("com.squareup.okhttp3:okhttp:3.12.12"){
force = true //API 19 support
}
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.12'
//retrofit
implementation "com.squareup.retrofit2:retrofit:2.7.1"
implementation "com.squareup.retrofit2:converter-scalars:$2.7.1"
Also Java 8 compatibility
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
With the service
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Headers
import retrofit2.http.POST
interface GraphQLService {
#Headers("Content-Type: application/json")
#POST("/")
suspend fun postDynamicQuery(#Body body: String): Response<String>
}
you can create a object
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
object GraphQLInstance {
private const val BASE_URL: String = "http://192.155.1.55:2000/"
val graphQLService: GraphQLService by lazy {
Retrofit
.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build().create(GraphQLService::class.java)
}
}
In the activity you can create this method
private fun post(userId: String){
val retrofit = GraphQLInstance.graphQLService
val paramObject = JSONObject()
paramObject.put("query", "query {users(userid:$userId){username}}")
GlobalScope.launch {
try {
val response = retrofit.postDynamicQuery(paramObject.toString())
Log.e("response", response.body().toString())
}catch (e: java.lang.Exception){
e.printStackTrace()
}
}
}
You can check the example in GitHub and my post
Note: if you need a mutation should be to change this line
paramObject.put("query", "query {users(userid:$userId){username}}")
to
paramObject.put("query", "mutation {users(userid:$userId){username}}")
personally I use Retrofit and I took this Link Credits
and changed some things.
This is the code:
In File "GraphQLConverter.java":
public class GraphQLConverter extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private GraphQueryProcessor graphProcessor;
private final Gson mGson;
private GraphQLConverter(Context context) {
graphProcessor = new GraphQueryProcessor(context);
mGson = new GsonBuilder()
.enableComplexMapKeySerialization()
.setLenient()
.create();
}
public static GraphQLConverter create(Context context) {
return new GraphQLConverter(context);
}
/** Override Converter.Factory Methods **/
#Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return null;
}
#Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if(type == QueryContainerBuilder.class){
return new GraphRequestConverter(methodAnnotations);
} else {
return null;
}
}
/** RequestConverter Class **/
private class GraphRequestConverter implements Converter<QueryContainerBuilder, RequestBody> {
private Annotation[] mAnnotations;
private GraphRequestConverter(Annotation[] annotations) {
mAnnotations = annotations;
}
#Override
public RequestBody convert(#NonNull QueryContainerBuilder containerBuilder) {
QueryContainerBuilder.QueryContainer queryContainer = containerBuilder
.setQuery(graphProcessor.getQuery(mAnnotations))
.build();
return RequestBody.create(MEDIA_TYPE, mGson.toJson(queryContainer).getBytes());
}
}
}
In File "GraphQuery.java":
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface GraphQuery {
String value() default "";
}
In File "GraphQueryProcessor.java":
class GraphQueryProcessor {
private static final String TAG = GraphQueryProcessor.class.getSimpleName();
// GraphQl Constants
private static final String EXT_GRAPHQL = ".graphql";
private static final String ROOT_FOLDER_GRAPHQL = "graphql";
private final Map<String, String> mGraphQueries;
private Context mContext;
GraphQueryProcessor(Context context) {
mGraphQueries = new WeakHashMap<>();
mContext = context;
populateGraphQueries(ROOT_FOLDER_GRAPHQL);
}
/** Package-Private Methods **/
String getQuery(Annotation[] annotations) {
if(mGraphQueries == null || mGraphQueries.isEmpty()){
populateGraphQueries(ROOT_FOLDER_GRAPHQL);
}
GraphQuery graphQuery = null;
for (Annotation annotation : annotations) {
if (annotation instanceof GraphQuery) {
graphQuery = (GraphQuery) annotation;
break;
}
}
if (graphQuery != null) {
String fileName = String.format("%s%s", graphQuery.value(), EXT_GRAPHQL);
if (mGraphQueries != null && mGraphQueries.containsKey(fileName)) {
return mGraphQueries.get(fileName);
}
}
return null;
}
/** Private Methods **/
private void populateGraphQueries(#NonNull String path) {
try {
String[] paths = mContext.getAssets().list(path);
if (paths != null && paths.length > 0x0) {
for (String item : paths) {
String absolute = path + "/" + item;
if (!item.endsWith(EXT_GRAPHQL)) {
populateGraphQueries(absolute);
} else {
mGraphQueries.put(item, getFileContents(mContext.getAssets().open(absolute)));
}
}
}
} catch (IOException ioE) {
BaseEnvironment.onExceptionLevelLow(TAG, ioE);
}
}
private String getFileContents(InputStream inputStream) {
StringBuilder queryBuffer = new StringBuilder();
try {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
for (String line; (line = bufferedReader.readLine()) != null; )
queryBuffer.append(line);
inputStreamReader.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return queryBuffer.toString();
}
}
In File "QueryContainerBuilder.java":
public class QueryContainerBuilder {
// Mask Types
private static final byte MASK_REPLACE_QUERY_ARGUMENTS = 0b1; // Invece di inviare il json con le variabili va a inserirle nella query i valori sostituendo i tipi degli argomenti.
private static final byte MASK_REPLACE_EXPLICIT_QUOTES = MASK_REPLACE_QUERY_ARGUMENTS << 0b1; // Alle stringhe non vengono automaticamente messe le virgolette ma devono essere aggiunte nei valori passati per le variabili.
private static final byte MASK_REPLACE_WITH_PLACEHOLDERS = MASK_REPLACE_EXPLICIT_QUOTES << 0b1; // Va a sostituire i placeholders "<key_var_name>" presenti nella query con i valori delle variabili.
private QueryContainer mQueryContainer;
private byte mMask;
public QueryContainerBuilder() {
mQueryContainer = new QueryContainer();
}
/** Setter Methods **/
public QueryContainerBuilder setQuery(String query) {
mQueryContainer.setQuery(query);
return this;
}
public QueryContainerBuilder setReplaceQueryArguments(){
mMask = MASK_REPLACE_QUERY_ARGUMENTS;
return this;
}
public QueryContainerBuilder setReplaceExplicitQuotes(){
mMask = MASK_REPLACE_QUERY_ARGUMENTS | MASK_REPLACE_EXPLICIT_QUOTES;
return this;
}
public QueryContainerBuilder setReplaceWithPlaceholders(){
mMask = MASK_REPLACE_QUERY_ARGUMENTS | MASK_REPLACE_WITH_PLACEHOLDERS;
return this;
}
/** Public Methods **/
public QueryContainerBuilder putVariable(String key, Object value) {
mQueryContainer.putVariable(key, value);
return this;
}
public boolean containsVariable(String key) {
return mQueryContainer.containsVariable(key);
}
/** Builder Methods **/
public QueryContainer build() {
if((mMask & MASK_REPLACE_QUERY_ARGUMENTS) != 0x0){
if((mMask & MASK_REPLACE_WITH_PLACEHOLDERS) != 0x0){
mQueryContainer.replaceVariablesPlaceholdersInQuery();
} else {
mQueryContainer.replaceVariablesInQuery(mQueryContainer.mVariables, 0x0);
}
mQueryContainer.mVariables = null;
}
return mQueryContainer;
}
/** Public Static Classes **/
public class QueryContainer {
#SerializedName("variables")
private LinkedHashMap<String, Object> mVariables;
#SerializedName("query")
private String mQuery;
QueryContainer() {
mVariables = new LinkedHashMap<>();
}
/** Private Methods **/
private void setQuery(String query) {
mQuery = query;
}
private void putVariable(String key, Object value) {
mVariables.put(key, value);
}
private boolean containsVariable(String key) {
return mVariables != null && mVariables.containsKey(key);
}
private void replaceVariablesInQuery(LinkedHashMap<String, Object> map, int index){
if(!TextUtils.isEmpty(mQuery) && map.size() > 0x0){
List<String> keys = new ArrayList<>(map.keySet());
for(String key : keys){
Object value = map.get(key);
if(value instanceof LinkedHashMap){
replaceVariablesInQuery((LinkedHashMap<String, Object>) value, index);
} else {
int i = mQuery.indexOf(key + ":", index) + key.length() + 0x1;
int z;
if(keys.indexOf(key) < keys.size() - 0x1){
z = mQuery.indexOf(",", i);
} else {
z = mQuery.indexOf(")", i);
int x = mQuery.substring(i, z).indexOf('}');
if(x != -0x1){
if(mQuery.substring(i, i + 0x4).contains("{")){
x++;
}
z -= ((z - i) - x);
}
}
String replace;
if((mMask & MASK_REPLACE_EXPLICIT_QUOTES) != 0x0){
replace = String.valueOf(value);
} else {
replace = value instanceof String ?
"\"" + value.toString() + "\"" : String.valueOf(value);
}
String sub = mQuery.substring(i, z)
.replaceAll("[\\\\]?\\[", "\\\\\\[").replaceAll("[\\\\]?\\]", "\\\\\\]")
.replaceAll("[\\\\]?\\{", "\\\\\\{").replaceAll("[\\\\]?\\}", "\\\\\\}");
mQuery = mQuery.replaceFirst(sub.contains("{}") ? sub.replace("{}", "").trim() : sub.trim(), replace);
index = z + 0x1;
}
}
}
}
private void replaceVariablesPlaceholdersInQuery(){
if(!TextUtils.isEmpty(mQuery) && mVariables.size() > 0x0){
for(String key : mVariables.keySet()){
mQuery = mQuery.replaceFirst("\\<" + key + "\\>", mVariables.get(key) != null ? mVariables.get(key).toString() : "null");
}
mVariables = null;
}
}
}
}
Put your queries in a "graphql" directory in the "assets" folder with the ".graphql" extension for your query files. You can change the extension or the folder by changing the "EXT_GRAPHQL" or "ROOT_FOLDER_GRAPHQL" constants in "GraphQueryProcessor". You can use these formats for the queries:
query {
myQuery(param1: <myParam1>) {
....
}
}
If you use this format you need to use "MASK_REPLACE_WITH_PLACEHOLDERS" in your QueryContainerBuilder. Also you need to pass as the HashMap key the name of the placeholder without the "<...>", so in this case "myParam1".
The others format are just common GraphQL queries, like:
query ($p1: String!) {
muQuery(p1: $id) {
...
}
}
With this format you can use normal QueryContainerBuilder behaviour (no mask applyed, so it will pass and generate the "variables" json object.) or the "MASK_REPLACE_QUERY_ARGUMENTS" which will remove the "$id" and place the value.
When you init Retrofit add the "GraphQLConverter". Take care about the "ConvertFactories" order! You can put more ConvertFactory, but they consume the input so if in this case you put "Gson" before "GraphQL" the "GsonConverted" will consume the input data:
new Retrofit.Builder()
.baseUrl(mBaseUrl)
.addConverterFactory(GraphQLConverter.create(context))
.addConverterFactory(GsonConverterFactory.create(gson))
.client(getBaseHttpClient(interceptor))
.build();
In your Retrofit API:
#POST(AppConstants.SERVICE_GQL)
#GraphQuery(AppConstants.MY_GRAPHQL_QUERY_FILENAME)
fun callMyGraphQlQuery(#Body query: QueryContainerBuilder): Call<MyGraphQlResponse>
Call examples:
val query = QueryContainerBuilder()
.putVariable("myParam1", myValue)
.setReplaceWithPlaceholders()
createService(API::class.java).callMyGraphQlQuery(query)
val query = QueryContainerBuilder()
.putVariable("p1", myValue)
.setReplaceQueryArguments()
createService(API::class.java).callMyGraphQlQuery(query)
val query = QueryContainerBuilder()
.putVariable("p1", myValue)
createService(API::class.java).callMyGraphQlQuery(query)
Idk if the "MASK_REPLACE_QUERY_ARGUMENTS" works right, I used it only 2/3 times and then the back-end was changed and wrote better.
I did those cases (masks) to process the queries because I had this 3 case of queries with the back-end I was calling.
You can just add others query processing behavior just by adding another mask and the code in the "QueryContainerBuilder".
If anyone use this code and change it making it better, please write me the changes so I will change the code in my library too.
Thanks you,
have a nice coding and day :D
Bye!