Java Code Examples for io.reactivex.Single#fromCallable()

The following examples show how to use io.reactivex.Single#fromCallable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TokensRealmSource.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@Override
public Single<TokenTicker> fetchTicker(Wallet wallet, Token token) {
    return Single.fromCallable(() -> {
        TokenTicker tokenTicker = null;
        try (Realm realm = realmManager.getRealmInstance(wallet))
        {
            RealmTokenTicker rawItem = realm.where(RealmTokenTicker.class)
                    .equalTo("contract", token.getAddress() + "-" + token.tokenInfo.chainId)
                    .findFirst();

            tokenTicker = convertRealmTicker(rawItem);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return tokenTicker == null
                ? new TokenTicker()
                : tokenTicker;
    });
}
 
Example 2
Source File: AlphaWalletService.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private Single<int[]> generateTicketArray(String indices, Ticket ticket)
{
    return Single.fromCallable(() -> {
        List<Integer> ticketIndices = ticket.stringIntsToIntegerList(indices);
        int[] indicesArray = new int[ticketIndices.size()];
        for (int i = 0; i < ticketIndices.size(); i++) indicesArray[i] = ticketIndices.get(i);
        return indicesArray;
    });
}
 
Example 3
Source File: FavoriteStore.java    From Android-App-Architecture-MVVM-Databinding with Apache License 2.0 5 votes vote down vote up
@Override
public Single<Boolean> deleteFavoriteMovie(@NonNull final MovieData movie) {
    return Single.fromCallable(() -> {
        final FavoriteDao dao = favoriteDatabase.getDao();
        return dao.deleteFavorite(movie.getId()) == 1;
    });
}
 
Example 4
Source File: WalletDataRealmSource.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public Single<Boolean> getWalletBackupWarning(String walletAddr)
{
    return Single.fromCallable(() -> {
        long backupTime = getKeyBackupTime(walletAddr);
        long warningTime = getWalletWarningTime(walletAddr);
        return requiresBackup(backupTime, warningTime);
    });
}
 
Example 5
Source File: TransactionRepository.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private Single<byte[]> encodeTransaction(byte[] signatureBytes, RawTransaction rtx)
{
	return Single.fromCallable(() -> {
		Sign.SignatureData sigData = sigFromByteArray(signatureBytes);
		if (sigData == null) return FAILED_SIGNATURE.getBytes();
		return encode(rtx, sigData);
	});
}
 
Example 6
Source File: RedeemSignatureDisplayModel.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private Single<Boolean> closeListener()
{
    return Single.fromCallable(() -> {
        try {
            memPoolSubscription.dispose();
            return true;
        } catch (NetworkOnMainThreadException th) {
            // Ignore all errors, it's not important source.
            return false;
        }
    });
}
 
Example 7
Source File: WrappedEntityStore.java    From requery with Apache License 2.0 5 votes vote down vote up
@Override
public <K, E extends T> Single<K> insert(final E entity, final Class<K> keyClass) {
    return Single.fromCallable(new Callable<K>() {
        @Override
        public K call() throws Exception {
            return delegate.insert(entity, keyClass);
        }
    });
}
 
Example 8
Source File: TransactionRepository.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
@Override
public Single<ContractType> queryInterfaceSpec(String address, TokenInfo tokenInfo)
{
	NetworkInfo networkInfo = networkRepository.getNetworkByChain(tokenInfo.chainId);
	ContractType checked = TokensService.checkInterfaceSpec(tokenInfo.chainId, tokenInfo.address);
	if (tokenInfo.name == null && tokenInfo.symbol == null)
	{
		return Single.fromCallable(() -> ContractType.NOT_SET);
	}
	else if (checked != null && checked != ContractType.NOT_SET && checked != ContractType.OTHER)
	{
		return Single.fromCallable(() -> checked);
	}
	else return blockExplorerClient.checkConstructorArgs(networkInfo, address);
}
 
Example 9
Source File: GetSingleOperation.java    From HighLite with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches a single row from a database and maps it to and object of type {@link T},
 * non-blocking operation.
 *
 * @return a {@link Single<T>} where an object of type {@link T} mapped from a database
 * record is passed as the parameter to
 * {@link io.reactivex.observers.DisposableSingleObserver#onSuccess(Object)}
 */
@Override
public Single<T> asSingle() {
    return Single.fromCallable(new Callable<T>() {
        @Override
        public T call() {
            return executeBlocking();
        }
    });
}
 
Example 10
Source File: TransactionRepository.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private Single<String> storeUnconfirmedTransaction(Wallet from, String txHash, String toAddress, BigInteger value, BigInteger gasPrice, int chainId, String data)
{
	return Single.fromCallable(() -> {

		Transaction newTx = new Transaction(txHash, "0", "0", System.currentTimeMillis()/1000, 0, from.address, toAddress, value.toString(10), "0", gasPrice.toString(10), data,
				"0", chainId, "");
		inDiskCache.putTransaction(from, newTx);

		return txHash;
	});
}
 
Example 11
Source File: AppRepositoryImpl.java    From Open-Mam with Apache License 2.0 5 votes vote down vote up
public Single<List<AppVersion>> application(String name) {
    return Single.fromCallable(() -> Arrays.asList(
            new AppVersion("1.0.0", "38", "22/11/2017 23h59", ""),
            new AppVersion("1.0.0", "38", "22/11/2017 23h59", ""),
            new AppVersion("1.0.0", "38", "22/11/2017 23h59", ""),
            new AppVersion("1.0.0", "38", "22/11/2017 23h59", ""),
            new AppVersion("1.0.0", "38", "22/11/2017 23h59", ""),
            new AppVersion("1.0.0", "38", "22/11/2017 23h59", ""),
            new AppVersion("1.0.0", "38", "22/11/2017 23h59", ""),
            new AppVersion("1.0.0", "38", "22/11/2017 23h59", ""),
            new AppVersion("1.0.0", "38", "22/11/2017 23h59", "")
    ));
}
 
Example 12
Source File: CompiledDelete.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link Single} that when subscribed to executes this compiled
 * delete statement against a database and emits nr of deleted records to downstream
 * only once.
 *
 * @return Deferred {@link Single} that when subscribed to executes the statement and emits
 * its result to downstream
 */
@NonNull
@CheckResult
public Single<Integer> observe() {
  return Single.fromCallable(new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
      return execute();
    }
  });
}
 
Example 13
Source File: WrappedEntityStore.java    From requery with Apache License 2.0 5 votes vote down vote up
@Override
public <E extends T> Single<E> insert(final E entity) {
    return Single.fromCallable(new Callable<E>() {
        @Override
        public E call() throws Exception {
            return delegate.insert(entity);
        }
    });
}
 
Example 14
Source File: LocalDbRepositoryImpl.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Single<Integer> getWaitingResultTimeout() {
    return Single.fromCallable(() ->
            context.getSharedPreferences(CONFIG_FILE, Context.MODE_PRIVATE)
                    .getInt(KEY_WAITING_RESULT_TIMEOUT, 120)
    );
}
 
Example 15
Source File: AssetDefinitionService.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
private Single<File> fetchXMLFromServer(String address)
{
    return Single.fromCallable(() -> {
        final File defaultReturn = new File("");
        if (address.equals("")) return defaultReturn;

        File result = getDownloadedXMLFile(address);

        //peek to see if this file exists
        long fileTime = 0;
        if (result != null && result.exists())
        {
            TokenDefinition td = getTokenDefinition(result);
            if (definitionIsOutOfDate(td))
            {
                removeFile(result.getAbsolutePath());
                assetChecked.put(address, 0L);
            }
            else
            {
                fileTime = result.lastModified();
            }
        }
        else
        {
            result = defaultReturn;
        }

        if (assetChecked.get(address) != null && (System.currentTimeMillis() > (assetChecked.get(address) + 1000L*60L*60L))) return result;

        SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.ENGLISH);
        format.setTimeZone(TimeZone.getTimeZone("UTC"));
        String dateFormat = format.format(new Date(fileTime));

        StringBuilder sb = new StringBuilder();
        sb.append(TOKENSCRIPT_REPO_SERVER);
        sb.append(TOKENSCRIPT_CURRENT_SCHEMA);
        sb.append("/");
        sb.append(address);

        //prepare Android headers
        PackageManager manager = context.getPackageManager();
        PackageInfo info = manager.getPackageInfo(
                context.getPackageName(), 0);
        String appVersion = info.versionName;
        String OSVersion = String.valueOf(Build.VERSION.RELEASE);

        okhttp3.Response response = null;

        try
        {
            Request request = new Request.Builder()
                    .url(sb.toString())
                    .get()
                    .addHeader("Accept", "text/xml; charset=UTF-8")
                    .addHeader("X-Client-Name", "AlphaWallet")
                    .addHeader("X-Client-Version", appVersion)
                    .addHeader("X-Platform-Name", "Android")
                    .addHeader("X-Platform-Version", OSVersion)
                    .addHeader("If-Modified-Since", dateFormat)
                    .build();

            response = okHttpClient.newCall(request).execute();

            switch (response.code())
            {
                case HttpURLConnection.HTTP_NOT_MODIFIED:
                    result = defaultReturn;
                    break;
                case HttpURLConnection.HTTP_OK:
                    String xmlBody = response.body().string();
                    result = storeFile(address, xmlBody);
                    break;
                default:
                    result = defaultReturn;
                    break;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (response != null) response.body().close();
        }

        assetChecked.put(address, System.currentTimeMillis());

        return result;
    });
}
 
Example 16
Source File: TrackedEntityInstanceQueryCollectionRepository.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Single<List<TrackedEntityInstance>> get() {
    return Single.fromCallable(this::blockingGet);
}
 
Example 17
Source File: TransactionRepository.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
private Single<Transaction[]> noTransactions()
{
	return Single.fromCallable(() -> new Transaction[0]);
}
 
Example 18
Source File: LocalDbRepositoryImpl.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Single<String> getUserName() {
    return Single.fromCallable(() -> userModule.authenticatedUser().blockingGet().user());
}
 
Example 19
Source File: Geocoding.java    From RxGps with Apache License 2.0 4 votes vote down vote up
public Single<List<Address>> fromLocationName(Locale locale, @NonNull String locationName, int maxResults) {
    return Single.fromCallable(() -> getGeocoder(locale).getFromLocationName(locationName, maxResults));
}
 
Example 20
Source File: TrackedEntityInstanceListDownloadAndPersistCallFactory.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Single<List<TrackedEntityInstance>> getCall(final Collection<String> trackedEntityInstanceUids,
                                                   final String program) {
    return Single.fromCallable(() -> downloadAndPersistBlocking(trackedEntityInstanceUids, program));
}