Search in sources :

Example 61 with Observable

use of io.reactivex.Observable in project RxCache by VictorAlbertos.

the class GetProvidersClass method getMethods.

private List<ProvidersClass.Method> getMethods(Element classElement) throws ValidationException {
    List<? extends Element> enclosedElements = classElement.getEnclosedElements();
    List<ProvidersClass.Method> methods = new ArrayList<>();
    for (Element methodElement : enclosedElements) {
        if (!isAnnotatedWithActionable(methodElement))
            continue;
        if (methodElement.getKind() != ElementKind.METHOD)
            continue;
        Symbol.MethodSymbol methodSymbol = (Symbol.MethodSymbol) methodElement;
        String nameMethod = methodSymbol.getSimpleName().toString();
        Type returnType = methodSymbol.getReturnType();
        if (!returnType.tsym.toString().equals(TypeName.get(Observable.class).toString())) {
            throw new ValidationException(methodSymbol, "Error parsing %s provider. Only Observable<List> type is supported as observable loader", nameMethod);
        }
        Type enclosingTypeObservable = returnType.getTypeArguments().get(0);
        if (!enclosingTypeObservable.tsym.toString().equals(TypeName.get(List.class).toString())) {
            throw new ValidationException(methodSymbol, "Error parsing %s provider. Only Observable<List> type is supported as observable loader", nameMethod);
        }
        List<Symbol.VarSymbol> params = methodSymbol.getParameters();
        boolean hasEvictProvider = hasEvictProvider(params);
        boolean hasEvictDynamicKey = hasEvictDynamicKey(params);
        boolean hasEvictDynamicKeyGroup = hasEvictDynamicKeyGroup(params);
        if (!hasEvictProvider && !hasEvictDynamicKey && !hasEvictDynamicKeyGroup) {
            throw new ValidationException(methodElement, "Error parsing %s provider. The provider requires one evicting argument: EvictProvider, EvictDynamicKey or EvictDynamicKeyGroup", nameMethod);
        }
        if (hasEvictProvider && hasEvictDynamicKey) {
            throw new ValidationException(methodElement, "Error parsing %s provider. The provider requires one evicting argument: EvictProvider, EvictDynamicKey or EvictDynamicKeyGroup", nameMethod);
        }
        if (hasEvictProvider && hasEvictDynamicKeyGroup) {
            throw new ValidationException(methodElement, "Error parsing %s provider. The provider requires one evicting argument: EvictProvider, EvictDynamicKey or EvictDynamicKeyGroup", nameMethod);
        }
        if (hasEvictDynamicKey && hasEvictDynamicKeyGroup) {
            throw new ValidationException(methodElement, "Error parsing %s provider. The provider requires one evicting argument: EvictProvider, EvictDynamicKey or EvictDynamicKeyGroup", nameMethod);
        }
        boolean hasDynamicKey = hasDynamicKey(params);
        boolean hasDynamicKeyGroup = hasDynamicKeyGroup(params);
        methods.add(new ProvidersClass.Method(nameMethod, methodElement, enclosingTypeObservable, hasDynamicKey, hasDynamicKeyGroup));
    }
    return methods;
}
Also used : Symbol(com.sun.tools.javac.code.Symbol) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) ArrayList(java.util.ArrayList) Observable(io.reactivex.Observable) Type(com.sun.tools.javac.code.Type) List(java.util.List) ArrayList(java.util.ArrayList)

Example 62 with Observable

use of io.reactivex.Observable in project RxCache by VictorAlbertos.

the class ProxyProviders method invoke.

@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    return Observable.defer(new Callable<ObservableSource<?>>() {

        @Override
        public ObservableSource<?> call() throws Exception {
            Observable observable = processorProviders.process(proxyTranslator.processMethod(method, args));
            Class<?> methodType = method.getReturnType();
            if (methodType == Observable.class)
                return Observable.just(observable);
            if (methodType == Single.class)
                return Observable.just(Single.fromObservable(observable));
            if (methodType == Maybe.class) {
                return Observable.just(Maybe.fromSingle(Single.fromObservable(observable)));
            }
            if (method.getReturnType() == io.reactivex.Flowable.class) {
                return Observable.just(observable.toFlowable(BackpressureStrategy.MISSING));
            }
            String errorMessage = method.getName() + io.rx_cache2.internal.Locale.INVALID_RETURN_TYPE;
            throw new RuntimeException(errorMessage);
        }
    }).blockingFirst();
}
Also used : Callable(java.util.concurrent.Callable) Observable(io.reactivex.Observable)

Example 63 with Observable

use of io.reactivex.Observable in project mosby by sockeqwe.

the class MainMenuPresenter method bindIntents.

@Override
protected void bindIntents() {
    Observable<List<String>> loadCategories = intent(MainMenuView::loadCategoriesIntent).doOnNext(categoryName -> Timber.d("intent: load category %s", categoryName)).flatMap(ignored -> backendApi.getAllCategories().subscribeOn(Schedulers.io()));
    Observable<String> selectCategory = intent(MainMenuView::selectCategoryIntent).doOnNext(categoryName -> Timber.d("intent: select category %s", categoryName)).startWith(MainMenuItem.HOME);
    List<Observable<?>> allIntents = new ArrayList<>(2);
    allIntents.add(loadCategories);
    allIntents.add(selectCategory);
    Observable<MenuViewState> menuViewStateObservable = Observable.combineLatest(allIntents, (Function<Object[], MenuViewState>) objects -> {
        List<String> categories = (List<String>) objects[0];
        String selectedCategory = (String) objects[1];
        List<MainMenuItem> categoriesItems = new ArrayList<MainMenuItem>(categories.size() + 1);
        categoriesItems.add(new MainMenuItem(MainMenuItem.HOME, selectedCategory.equals(MainMenuItem.HOME)));
        for (int i = 0; i < categories.size(); i++) {
            String category = categories.get(i);
            categoriesItems.add(new MainMenuItem(category, category.equals(selectedCategory)));
        }
        return new MenuViewState.DataState(categoriesItems);
    }).startWith(new MenuViewState.LoadingState()).onErrorReturn(MenuViewState.ErrorState::new).observeOn(AndroidSchedulers.mainThread());
    subscribeViewState(menuViewStateObservable, MainMenuView::render);
}
Also used : List(java.util.List) MviBasePresenter(com.hannesdorfmann.mosby3.mvi.MviBasePresenter) Function(io.reactivex.functions.Function) Observable(io.reactivex.Observable) Schedulers(io.reactivex.schedulers.Schedulers) ProductBackendApiDecorator(com.hannesdorfmann.mosby3.sample.mvi.businesslogic.http.ProductBackendApiDecorator) MainMenuItem(com.hannesdorfmann.mosby3.sample.mvi.businesslogic.model.MainMenuItem) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) Timber(timber.log.Timber) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) Observable(io.reactivex.Observable) Function(io.reactivex.functions.Function) List(java.util.List) ArrayList(java.util.ArrayList) MainMenuItem(com.hannesdorfmann.mosby3.sample.mvi.businesslogic.model.MainMenuItem)

Example 64 with Observable

use of io.reactivex.Observable in project nem2-sdk-java by nemtech.

the class AggregateTransactionServiceImpl method isComplete.

@Override
public Observable<Boolean> isComplete(SignedTransaction signedTransaction) {
    Validate.notNull(signedTransaction, "signedTransaction is required");
    Validate.isTrue(signedTransaction.getType() == TransactionType.AGGREGATE_COMPLETE, "signedTransaction type must be AGGREGATE_COMPLETE");
    AggregateTransaction transaction = (AggregateTransaction) BinarySerializationImpl.INSTANCE.deserialize(ConvertUtils.fromHexToBytes(signedTransaction.getPayload()));
    /*
     * Include both initiator & cosigners
     */
    Set<Address> signers = transaction.getCosignatures().stream().map(AggregateTransactionCosignature::getSigner).map(PublicAccount::getAddress).collect(Collectors.toSet());
    signers.add(signedTransaction.getSigner().getAddress());
    return Observable.fromIterable(transaction.getInnerTransactions()).flatMap(innerTransaction -> multisigRepository.getMultisigAccountInfo(innerTransaction.getSigner().orElseThrow(IllegalArgumentException::new).getAddress()).flatMap(multisigAccountInfo -> multisigAccountInfo.getMinRemoval() != 0 && multisigAccountInfo.getMinApproval() != 0 ? multisigRepository.getMultisigAccountGraphInfo(multisigAccountInfo.getAccountAddress()).map(graphInfo -> validateCosignatories(graphInfo, signers, innerTransaction)) : Observable.just(signers.stream().anyMatch(s -> s.equals(multisigAccountInfo.getAccountAddress()))))).all(v -> v).toObservable();
}
Also used : MultisigAccountInfo(io.nem.symbol.sdk.model.account.MultisigAccountInfo) AggregateTransactionCosignature(io.nem.symbol.sdk.model.transaction.AggregateTransactionCosignature) Set(java.util.Set) ConvertUtils(io.nem.symbol.core.utils.ConvertUtils) Transaction(io.nem.symbol.sdk.model.transaction.Transaction) RepositoryFactory(io.nem.symbol.sdk.api.RepositoryFactory) Collectors(java.util.stream.Collectors) MultisigAccountGraphInfo(io.nem.symbol.sdk.model.account.MultisigAccountGraphInfo) HashSet(java.util.HashSet) List(java.util.List) Stream(java.util.stream.Stream) Validate(org.apache.commons.lang3.Validate) PublicAccount(io.nem.symbol.sdk.model.account.PublicAccount) AggregateTransaction(io.nem.symbol.sdk.model.transaction.AggregateTransaction) TreeMap(java.util.TreeMap) MultisigRepository(io.nem.symbol.sdk.api.MultisigRepository) SignedTransaction(io.nem.symbol.sdk.model.transaction.SignedTransaction) Map(java.util.Map) NetworkRepository(io.nem.symbol.sdk.api.NetworkRepository) TransactionType(io.nem.symbol.sdk.model.transaction.TransactionType) Observable(io.reactivex.Observable) Address(io.nem.symbol.sdk.model.account.Address) MultisigAccountModificationTransaction(io.nem.symbol.sdk.model.transaction.MultisigAccountModificationTransaction) AggregateTransactionService(io.nem.symbol.sdk.api.AggregateTransactionService) Address(io.nem.symbol.sdk.model.account.Address) AggregateTransactionCosignature(io.nem.symbol.sdk.model.transaction.AggregateTransactionCosignature) AggregateTransaction(io.nem.symbol.sdk.model.transaction.AggregateTransaction)

Example 65 with Observable

use of io.reactivex.Observable in project nem2-sdk-java by nemtech.

the class PaginationStreamerTester method runSearch.

private void runSearch(int pageSize, int totalEntries, Integer limit) {
    try {
        criteria.setPageSize(pageSize);
        List<E> infos = IntStream.range(0, totalEntries).mapToObj((i) -> Mockito.mock(entityClass)).collect(Collectors.toList());
        Assertions.assertEquals(totalEntries, infos.size());
        List<Observable<Page<E>>> pages = toPages(infos, criteria.getPageSize());
        Mockito.when(repository.search(Mockito.eq(criteria))).thenAnswer(new ReturnsElementsOf(pages));
        Observable<E> search = streamer.search(criteria);
        if (limit != null) {
            search = search.take(limit);
        }
        List<E> returnedInfos = search.toList().toFuture().get();
        Assertions.assertEquals(infos.subList(0, limit == null ? infos.size() : limit), returnedInfos);
        int totalPagesRead = limit == null ? pages.size() : (int) Math.ceil(limit.doubleValue() / pageSize);
        Mockito.verify(repository, Mockito.times(totalPagesRead)).search(Mockito.eq(criteria));
    } catch (InterruptedException | ExecutionException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
Also used : ExecutionException(java.util.concurrent.ExecutionException) IntStream(java.util.stream.IntStream) Mockito(org.mockito.Mockito) List(java.util.List) ReturnsElementsOf(org.mockito.internal.stubbing.answers.ReturnsElementsOf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Assertions(org.junit.jupiter.api.Assertions) Observable(io.reactivex.Observable) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) ExecutionException(java.util.concurrent.ExecutionException) Observable(io.reactivex.Observable) ReturnsElementsOf(org.mockito.internal.stubbing.answers.ReturnsElementsOf)

Aggregations

Observable (io.reactivex.Observable)170 List (java.util.List)54 ArrayList (java.util.ArrayList)39 Test (org.junit.Test)36 Collectors (java.util.stream.Collectors)29 InOrder (org.mockito.InOrder)27 TestException (io.reactivex.exceptions.TestException)24 Page (io.nem.symbol.sdk.api.Page)19 Address (io.nem.symbol.sdk.model.account.Address)18 AndroidSchedulers (io.reactivex.android.schedulers.AndroidSchedulers)18 Disposable (io.reactivex.disposables.Disposable)18 Bundle (android.os.Bundle)17 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)16 Function (io.reactivex.functions.Function)15 TestObserver (io.reactivex.observers.TestObserver)15 Schedulers (io.reactivex.schedulers.Schedulers)15 Nullable (android.support.annotation.Nullable)14 MerkleStateInfo (io.nem.symbol.sdk.model.blockchain.MerkleStateInfo)14 ApiClient (io.nem.symbol.sdk.openapi.vertx.invoker.ApiClient)14 AsyncResult (io.vertx.core.AsyncResult)14