The official documents only describe how to use it in scala. http://www.playframework.com/documentation/2.1.0/ThreadPools.
Future {
// Some blocking or expensive code here
}(Contexts.myExecutionContext)
I can get the excutionContext like:
ExecutionContext myExecutionContext = Akka.system().dispatchers().lookup("my-context");
But how to add it in the code blow?
return async(
future(new Callable<String>() {
public String call() {
return doSth();
}).map(new F.Function<String,Result>() {
public Result apply(String i) {
return ok(i);
}
})
I think the answer should be:
ExecutionContext myExecutionContext = Akka.system().dispatchers().lookup("my-context");
return async(
Akka.asPromise(Futures.future(new Callable<String>() {
public String call() {
return doSth();
}
}, myExecutionContext)).map(new F.Function<String,Result>() {
public Result apply(String i) {
return ok(i);
}
})
);
Related
this is a method written in RxJava
public Observable<String> method() {
return model.getOffers()
.filter(new Func1<Offers, Boolean>() {
#Override
public Boolean call(Offers offers) {
if (offers == null)
return false;
return offers.hasSuperOffer();
}
})
.flatMap(new Func1<Offers, Observable<Long>>() {
#Override
public Observable<Long> call(Offers offers) {
Long offerEndTime = offers.getRemainingTime();
if (offerEndTime == null) {
return Observable.empty();
}
AtomicLong remainingTimeSec;
Long currentTimeSec = System.currentTimeMillis() / 1000;
if (remainingTimeSec.get() == -1 && (offerEndTime > currentTimeSec)) {
remainingTimeSec.set(offerEndTime - currentTimeSec);
} else {
return Observable.empty();
}
return Observable.interval(1, TimeUnit.SECONDS)
.onBackpressureDrop()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.take(remainingTimeSec.intValue())
.doOnUnsubscribe(new Action0() {
#Override
public void call() {
}
})
.doOnCompleted(new Action0() {
#Override
public void call() {
}
})
.map(new Func1<Long, Long>() {
#Override
public Long call(Long elapsedTimeSec) {
return remainingTimeSec.getAndDecrement();
}
});
}
})
.map(new Func1<Long, String>() {
#Override
public String call(Long remainingTime) {
return DateUtils.getRemainingTimeStr(remainingTime);
}
});
}
I am trying to convert it to RxJava3 but some parameters have changed:
Func1 has been changed to Function
Action0 has been changed to Action
After I'm making the changes the following error appears at filter:
filter (io.reactivex.rxjava3.functions#io.reactivex.rxjava3.annotations.NonNull Predicate <? MyClass> in Observable cannot be applied to (anonymous.io.reactivex.rxjava3.functions.Function <MyClass.model.Offers.java.lang.Boolean>)
Can anyone help me?
Thank you!
Today i was working on my homework, which it was making simple apps with retrofit calls and learning new things for code improvement, and somehow i saw there are so many ways to write less code and do better with OOP. So to improve my code experiment I'm trying to do my retrofit calls with OOP. So this is my issue right now:
Consider a simple retrofit call with CompositeDisposable( I'm developing my simples with MVP ) :
mView.showProgress(1);
RequestRemainingProductsRequest requestRemainingProductsRequest = new RequestRemainingProductsRequest();
requestRemainingProductsRequest.distributorId = distributorId;
requestRemainingProductsRequest.requestCode = requestCode;
requestRemainingProductsRequest.requestType = 1;
NetworkCalls.getObservableList();
compositeDisposable.add(getApi().requestRemainingProducts(requestRemainingProductsRequest)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<Products>>() {
#Override
public void accept(List<Products> products) throws Throwable {
mView.hideProgress(1);
mView.getRemainingProducts(products);
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
mView.hideProgress(1);
mView.showLog(throwable.getMessage().toString());
}
}));
And, Another retrofit call without CompositeDisposable :
ProductSellerRequest productSellerRequest = new ProductSellerRequest();
productSellerRequest.centralId = centralsList.get(i).requestCentralId;
productSellerRequest.requestType = 0;
productSellerRequest.productId = Constant.currentProduct.productId;
getApi().checkProductExistInRequest(productSellerRequest)
.enqueue(new Callback<ProductSellerCallback>() {
#Override
public void onResponse(Call<ProductSellerCallback> call, Response<ProductSellerCallback> response) {
hideProgress(myViewHolder);
showAddDialog(myViewHolder, v, response, i);
}
#Override
public void onFailure(Call<ProductSellerCallback> call, Throwable t) {
hideProgress(myViewHolder);
}
});
So let's say I created a java class with NetworkCalls.java, and created 2 voids like this:
public static void getObservableList()
{
}
public static void getWithoutObservableList()
{
}
How to handle my response to return to my Presenter/Activity?
This is how i using StringBuilder and returning my String, but I'm trying do similiar way to make repository for my Network Calls, then learn all all i should know about Repository Pattern.
public static String TotalPriceStringBuilder(int Price){
String DecimalPrice = String.format("%,d", Price);
String FinalString = new StringBuilder("Price : ").append(DecimalPrice).append(" $").toString();
return String.valueOf(FinalString);
}
This is what I've tried, but i still don't know how to fix it or make it work, what to return, and how to return and etc... :
private static ApiClient mApi;
private List<Products> receivedProducts;
private int hideProgress;
private boolean status;
private String message;
public void getObservableList(RequestRemainingProductsRequest requestRemainingProductsRequest, CompositeDisposable compositeDisposable)
{
compositeDisposable.add(getApi().requestRemainingProducts(requestRemainingProductsRequest)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<Products>>() {
#Override
public void accept(List<Products> products) throws Throwable {
hideProgress = 1;
receivedProducts = products;
status = TRUE;
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
hideProgress = 1;
status = FALSE;
message = throwable.getMessage().toString();
}
}));
if (status == TRUE) {
return hideProgress, receivedProducts, status;
} else {
return hideProgress, message, status;
}
}
public ApiClient getApi() {
if (mApi == null) {
mApi = ApiService.getClient().create(ApiClient.class);
}
return mApi;
}
If i use static method I'll get bunch of errors like can't be refrenced from a static context or etc...
I'm implementing a web service respecting version 4 of the OData standard in Java language with the framework Olingo. I need to customize the response of $filter. I've implemented a Visitor as documented in the quick start. I need to implement an integration Test to try a different kind of grammar and to prevent regression bug in case of future maintenance.
For the V2, I found the following tutorial and the following code :
#Test
public void printExpressionWithProperty() throws Exception {
//Use a mocked edmProvider for this tutorial
TestEdmProvider provider = new TestEdmProvider();
Edm edm = RuntimeDelegate.createEdm(provider);
EdmEntityType entityType = edm.getEntityType(TestEdmProvider.NAMESPACE_1, TestEdmProvider.ENTITY_TYPE_1_1.getName());
String rawExpression = "EmployeeId eq '1'";
FilterExpression expression = UriParser.parseFilter (null, entityType, rawExpression);
String whereClause = (String) expression.accept(new JdbcSimpleStringVisitor());
System.out.println("Raw: " + rawExpression + " ------> Whereclause: " + whereClause);
System.out.println();
}
Unfortunately, UriParser.parseFilter doesn't exist in the v4.
I tried this :
public class MyVisitorTest {
private final FullQualifiedName NAME1 = new FullQualifiedName("testNamespace1", "myfield");
private final OData odata = OData.newInstance();
public EdmEntityType createEntityType(final FullQualifiedName fqn) {
if (NAME1.equals(fqn)) {
EdmEntityType entityType = mock(EdmEntityType.class);
when(entityType.getNamespace()).thenReturn(fqn.getNamespace());
when(entityType.getName()).thenReturn(fqn.getName());
return entityType;
}
return null;
}
private Expression parseExpression(final String expressionString)
throws UriParserException, UriValidationException {
UriTokenizer tokenizer = new UriTokenizer(expressionString);
EdmEntityType entityType = createEntityType(NAME1);
Edm edm = mock(Edm.class);
when(edm.getEntityType(NAME1)).thenReturn(entityType);
final Expression expression = new ExpressionParser(edm, odata).parse(tokenizer, null, null, null);
assertNotNull(expression);
assertTrue(tokenizer.next(UriTokenizer.TokenKind.EOF));
return expression;
}
#Test
public void simpleTest() throws UriParserException, UriValidationException, ODataApplicationException, ExpressionVisitException {
String exp = "myfield gt 2019-01-01T00:00:00Z";
Expression e = parseExpression(exp);
MyVisitor myVisitor = new MyVisitor();
String result = (String) e.accept(startEndMeasureVisitor);
assertEquals(result.toString(), "MyResult");
}
}
And it doesn't work, it sends me the following message :
Property paths must follow a structured type.
So I'm looking for any ideas to make my unit test to work or if you've got working example to share...
When it comes to unit tests, I'd focus on testing every filter method separately. Like if visitBinaryOperator returns an expected value based on the input and so on.
I'm not an expert in naming things, but I'd call your test an integration test. Here, I'd focus on testing FilterOption prepared inside the test. In your original app, Apache Olingo will create this FilterOption and this part is (should be) tested in Olingo.
When I worked with Apache Olingo I was frequently referring to its repository, especially to server-test and server-tecsvc. To verify how things are tested in Olingo itself.
I'd recommend to take a look at FilterValidator as it may be something useful for your integration test.
Here we go, thanks to tracing function of mockup (very usefull with legacy code), I've got the new version of parseExpression method that answer my question.
class A implements EdmStructuredType, EdmPrimitiveType {
#Override
public boolean isCompatible(EdmPrimitiveType edmPrimitiveType) {
return false;
}
#Override
public Class<?> getDefaultType() {
return null;
}
#Override
public boolean validate(String s, Boolean aBoolean, Integer integer, Integer integer1, Integer integer2, Boolean aBoolean1) {
return false;
}
#Override
public <T> T valueOfString(String s, Boolean aBoolean, Integer integer, Integer integer1, Integer integer2, Boolean aBoolean1, Class<T> aClass) throws EdmPrimitiveTypeException {
return null;
}
#Override
public String valueToString(Object o, Boolean aBoolean, Integer integer, Integer integer1, Integer integer2, Boolean aBoolean1) throws EdmPrimitiveTypeException {
return null;
}
#Override
public String toUriLiteral(String s) {
return null;
}
#Override
public String fromUriLiteral(String s) throws EdmPrimitiveTypeException {
return null;
}
#Override
public EdmElement getProperty(String s) {
return null;
}
#Override
public List<String> getPropertyNames() {
return null;
}
#Override
public EdmProperty getStructuralProperty(String s) {
return null;
}
#Override
public EdmNavigationProperty getNavigationProperty(String s) {
return null;
}
#Override
public List<String> getNavigationPropertyNames() {
return null;
}
#Override
public EdmStructuredType getBaseType() {
return null;
}
#Override
public boolean compatibleTo(EdmType edmType) {
return false;
}
#Override
public boolean isOpenType() {
return false;
}
#Override
public boolean isAbstract() {
return false;
}
#Override
public EdmAnnotation getAnnotation(EdmTerm edmTerm, String s) {
return null;
}
#Override
public List<EdmAnnotation> getAnnotations() {
return null;
}
#Override
public FullQualifiedName getFullQualifiedName() {
return null;
}
#Override
public String getNamespace() {
return null;
}
#Override
public EdmTypeKind getKind() {
return null;
}
#Override
public String getName() {
return null;
}
}
private Expression parseExpression(final String expressionString)
throws UriParserException, UriValidationException {
UriTokenizer tokenizer = new UriTokenizer(expressionString);
Edm edm = mock(A.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS));
EdmProperty employeeIdTypeEdmElement = mock(EdmProperty.class, RETURNS_SMART_NULLS);
when(edmType.getProperty("EmployeeId")).thenReturn(measureTypeEdmElement);
when(edmType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE);
when(edmType.isCompatible(new EdmDate())).thenReturn(true);
when(employeeIdTypeEdmElement.getName()).thenReturn("EmployeeId");
when(employeeIdTypeEdmElement.getType()).thenReturn(edmType);
when(employeeIdTypeEdmElement.isCollection()).thenReturn(false);
final Expression expression = new ExpressionParser(edm, odata).parse(tokenizer, edmType, null, null);
assertNotNull(expression);
assertTrue(tokenizer.next(UriTokenizer.TokenKind.EOF));
return expression;
}
In case it helps someone, maybee it can be optimized, fill free to propose.
I want to load the next item(s) when some other observable emits a new item (a trigger).
This is the code that emits the items:
public Observable<Item> get() {
return idApi.get().flatMap(new Function<List<String>, ObservableSource<String>>() {
#Override
public ObservableSource<String> apply(#NonNull List<String> ids) throws Exception {
return Observable.fromIterable(ids);
}
}).flatMap(new Function<String, ObservableSource<Item>>() {
#Override
public ObservableSource<Item> apply(#NonNull final String id) throws Exception {
return dataApi.get(id).map(new Function<Data, Item>() {
#Override
public Item apply(#NonNull Data data) throws Exception {
return new Item(data , id);
});
}
});
}
Trigger Observable:
RxView.clicks(view.findViewById(R.id.button_more)).debounce(500, TimeUnit.MILLISECONDS);
The only way I could get around this was using a Subject and holding a reference to a list of ids which wasn't elegant and didn't seem reactive.
Edit: This is my solution so far, but I had to subscribe to trigger event directly. I don't consider it elegant.
#Override
public Observable<Item> get(final Observable<Object> trigger) {
final PublishSubject<Item> subject = PublishSubject.create();
return idApi.get().flatMap(new Function<List<String>, ObservableSource<Queue<String>>>() {
#Override
public ObservableSource<Queue<String>> apply(#NonNull List<String> ids) throws Exception {
final Queue<String> q = new LinkedList<>(ids);
return Observable.just(q);
}
}).flatMap(new Function<Queue<String>, ObservableSource<Item>>() {
#Override
public ObservableSource<Item> apply(#NonNull final Queue<String> ids) throws Exception {
trigger.subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Object>() {
#Override
public void accept(#NonNull Object o) throws Exception {
if (ids.size() > 0) {
final String id = ids.poll();
dataApi.get(id).map(new Function<Data, Item>() {
#Override
public Item apply(#NonNull Data data) throws Exception {
return new Item(data, id) l
}
}).subscribe(new Consumer<Item>() {
#Override
public void accept(#NonNull Item item) throws Exception {
subject.onNext(item);
}
});
} else {
subject.onComplete();
}
}
});
return subject;
}
});
}
Use zip
public Observable<Item> get(View v) {
return idApi.get().flatMap(new Function<List<String>, ObservableSource<String>>() {
#Override
public ObservableSource<String> apply(#NonNull List<String> ids) throws Exception {
return Observable.fromIterable(ids);
}
}).zipWith(RxView.clicks(v).debounce(500, TimeUnit.MILLISECONDS), (n, i) -> n))
.flatMap(new Function<String, ObservableSource<Item>>() {
#Override
public ObservableSource<Item> apply(#NonNull final String id) throws Exception {
return dataApi.get(id).map(new Function<Data, Item>() {
#Override
public Item apply(#NonNull Data data) throws Exception {
return new Item(data , id);
});
}
});
}
to get N items with each click
public Observable<Item> getN(View v, int nitems) {
return idApi.get().flatMap(new Function<List<String>, ObservableSource<String>>() {
#Override
public ObservableSource<String> apply(#NonNull List<String> ids) throws Exception {
return Observable.fromIterable(ids);
}
}).buffer(nitems).zipWith(RxView.clicks(v).debounce(500, TimeUnit.MILLISECONDS), (n, i) -> n))
.flatMap(new Function<List<String>, ObservableSource<String>>() {
#Override
public ObservableSource<String> apply(#NonNull final List<String> ids) throws Exception {
return Observable.from(ids)
}
}
)
.flatMap(new Function<String, ObservableSource<Item>>() {
#Override
public ObservableSource<Item> apply(#NonNull final String id) throws Exception {
return dataApi.get(id).map(new Function<Data, Item>() {
#Override
public Item apply(#NonNull Data data) throws Exception {
return new Item(data , id);
});
}
}
});
}
Edit: You will still have to use subscribeOn to make sure you are on the main thread for RXView.clicks and on the IO thread for any networking.
Not so good but it works:
your get method:
Observable<Item> get(final String id){
return Observable.defer(() -> {
dataApi.get(id).map(new Function<Data, Item>() {
#Override
public Item apply(#NonNull Data data) throws Exception {
return new Item(data , id);
});
})
}
your click:
private List<String> ids = {//your id s}
private int current = 0;
RxView.clicks(view).flatmap(ignore -> get(ids.get(current++)))
.subscribe(//your Observer)
I'd like recommend that answer with zipwith(), seems better than my answer.
How can I add an observable to an Integer object, such that I get notified of every object update? In this case Integer number = 0; and I would like to get notified every time I add for example 1. Initially I just want to log the event. This is what I have so far, but I'm stuck.
code:
Subscriber<Integer> num = new Subscriber<Integer>() {
#Override
public void onNext(Integer num) { Log.d("RX", num.toString()); }
#Override
public void onError(Throwable e) { Log.d("RX", "error"); }
#Override
public void onCompleted() { Log.d("RX", "completed"); }
};
Observable.just(number)
/*.doOnNext(new Action1<Integer>() {
#Override
public void call(Integer integer) {
Log.d("RX", "Updated integer" + integer.toString());
}
})*/
/*.flatMap(new Func1<Integer, Observable<?>>() {
#Override
public Observable<?> call(Integer integer) {
Log.d("RX", "Updated integer" + integer.toString());
return Observable.just(number);
}
})*/
.subscribe(num);
Without knowing exactly what you are trying to achieve it's hard to give the best answer but you could implement an ObservableInteger class along the lines of the following:
public class ObservableInteger {
private Integer value;
private PublishSubject<Integer> subject = PublishSubject.create();
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
subject.onNext(value);
}
public Observable<Integer> getObservable() {
return subject.asObservable();
}
}
Then you are able to subscribe to it:
ObservableInteger obInt = new ObservableInteger();
Subscription s = obInt
.getObservable()
.subscribe(
integer -> {
// each time a new value is set
// it will be emitted here
},
Throwable::printStackTrace
);
I came across this post today and realized it is written for RxJava1. There are several changes in RxJava 2. Some of them affecting the above sample. (.subscribe returns a Disposable https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#subscription and .asObservable() is now .hide() in RxJava 2.0 https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#instance-methods)
Here is the RxJava2 compatible solution of Jahnolds answer:
public class ObservableInteger {
private Integer value;
private PublishSubject<Integer> subject = PublishSubject.create();
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
subject.onNext(value);
}
public Observable<Integer> getObservable() {
return subject.hide();
}
}
and subscribe like so:
ObservableInteger obInt = new ObservableInteger();
Disposable d = obInt
.getObservable()
.subscribe(
integer -> {
// each time a new value is set
// it will be emitted here
},
Throwable::printStackTrace
);