android.arch.lifecycle.LiveData Java Examples

The following examples show how to use android.arch.lifecycle.LiveData. 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: LocalUserDataSource.java    From MVVM with MIT License 7 votes vote down vote up
@Override
public LiveData<Lcee<User>> queryUserByUsername(String username) {
    final MediatorLiveData<Lcee<User>> data = new MediatorLiveData<>();
    data.setValue(Lcee.<User>loading());

    data.addSource(userService.queryByUsername(username), new Observer<User>() {
        @Override
        public void onChanged(@Nullable User user) {
            if (null == user) {
                data.setValue(Lcee.<User>empty());
            } else {
                data.setValue(Lcee.content(user));
            }
        }
    });
    return data;
}
 
Example #2
Source File: AssignmentRepository.java    From OmniList with GNU Affero General Public License v3.0 6 votes vote down vote up
public LiveData<Resource<List<Assignment>>> updateOrders(List<Assignment> assignments) {
    MutableLiveData<Resource<List<Assignment>>> result = new MutableLiveData<>();
    new NormalAsyncTask<>(result, () -> {
        ((AssignmentsStore) getStore()).updateOrders(assignments);
        return assignments;
    }).execute();
    return result;
}
 
Example #3
Source File: AvailableBalanceRepository.java    From bitshares_wallet with MIT License 6 votes vote down vote up
public LiveData<Resource<BitsharesAsset>> getTargetAvaliableBlance(String currency) {
    mCurrency = currency;
    LiveData<BitsharesAsset> balanceAssetListLiveData = bitsharesDao.queryTargetAvalaliableBalance(currency);
    result.addSource(
            balanceAssetListLiveData,
            data -> {
                result.removeSource(balanceAssetListLiveData);
                if (shouldFetch(data)) {
                    fetchFromNetwork(balanceAssetListLiveData);
                } else {
                    result.addSource(balanceAssetListLiveData, newData -> result.setValue(Resource.success(newData)));
                }
            });

    return result;
}
 
Example #4
Source File: LocalUserDataSource.java    From MVVM with MIT License 6 votes vote down vote up
@Override
public LiveData<Lcee<User>> queryUserByUsername(String username) {
    final MediatorLiveData<Lcee<User>> data = new MediatorLiveData<>();
    data.setValue(Lcee.<User>loading());

    data.addSource(userService.queryByUsername(username), new Observer<User>() {
        @Override
        public void onChanged(@Nullable User user) {
            if (null == user) {
                data.setValue(Lcee.<User>empty());
            } else {
                data.setValue(Lcee.content(user));
            }
        }
    });
    return data;
}
 
Example #5
Source File: UserRepository.java    From MVVM with MIT License 5 votes vote down vote up
public LiveData<Lcee<User>> getUser(String username) {
    if (NetworkUtils.isConnected(context)) {
        return remoteUserDataSource.queryUserByUsername(username);
    } else {
        return localUserDataSource.queryUserByUsername(username);
    }
}
 
Example #6
Source File: UserRepository.java    From MVVM with MIT License 5 votes vote down vote up
public LiveData<Lcee<User>> getUser(String username) {
//        if (NetworkUtils.isConnected(context)) {
            return remoteUserDataSource.queryUserByUsername(username);
//        } else {
//            return localUserDataSource.queryUserByUsername(username);
//        }
    }
 
Example #7
Source File: LiveEventBus.java    From LiveEventBus with Apache License 2.0 5 votes vote down vote up
private Object getObserverWrapper(@NonNull Observer<T> observer) throws Exception {
    Field fieldObservers = LiveData.class.getDeclaredField("mObservers");
    fieldObservers.setAccessible(true);
    Object objectObservers = fieldObservers.get(this);
    Class<?> classObservers = objectObservers.getClass();
    Method methodGet = classObservers.getDeclaredMethod("get", Object.class);
    methodGet.setAccessible(true);
    Object objectWrapperEntry = methodGet.invoke(objectObservers, observer);
    Object objectWrapper = null;
    if (objectWrapperEntry instanceof Map.Entry) {
        objectWrapper = ((Map.Entry) objectWrapperEntry).getValue();
    }
    return objectWrapper;
}
 
Example #8
Source File: AssignmentRepository.java    From OmniList with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Get all assignments to display fot today fragment: overdue assignments and those start today.
 *
 * @return the assignments */
public LiveData<Resource<List<Assignment>>> getToday() {
    MutableLiveData<Resource<List<Assignment>>> result = new MutableLiveData<>();
    new NormalAsyncTask<>(result, () -> {
        long todayEnd = TimeUtils.endToday().getTime();
        return getStore().get(AssignmentSchema.START_TIME + " <= " + todayEnd +
                " AND " + AssignmentSchema.PROGRESS + " != " + Constants.MAX_ASSIGNMENT_PROGRESS,
                AssignmentSchema.START_TIME + " DESC, " + AssignmentSchema.NOTICE_TIME, Status.NORMAL, false);
    }).execute();
    return result;
}
 
Example #9
Source File: UserViewModel.java    From MVVM with MIT License 5 votes vote down vote up
public LiveData<Lcee<User>> getUser() {
    if (null == ldUser) {
        ldUsername = new MutableLiveData<>();
        ldUser = Transformations.switchMap(ldUsername, new Function<String, LiveData<Lcee<User>>>() {
            @Override
            public LiveData<Lcee<User>> apply(String username) {
                return userRepository.getUser(username);
            }
        });
    }
    return ldUser;
}
 
Example #10
Source File: MarketTickerRepository.java    From bitshares_wallet with MIT License 5 votes vote down vote up
public LiveData<Resource<List<BitsharesMarketTicker>>> queryMarketTicker() {
    LiveData<List<BitsharesMarketTicker>> marketTickerListData = bitsharesDao.queryMarketTicker();
    result.addSource(marketTickerListData, data -> {
        result.removeSource(marketTickerListData);
        if (shouldFetch(data)) {
            fetchFromNetwork(marketTickerListData);
        } else {
            result.addSource(marketTickerListData, newData -> result.setValue(Resource.success(newData)));
        }
    });

    return result;
}
 
Example #11
Source File: LiveEventBusCore.java    From LiveEventBus with Apache License 2.0 5 votes vote down vote up
private int getObserverCount(LiveData liveData) {
    try {
        Field field = LiveData.class.getDeclaredField("mObservers");
        field.setAccessible(true);
        Object mObservers = field.get(liveData);
        Class<?> classOfSafeIterableMap = mObservers.getClass();
        Method size = classOfSafeIterableMap.getDeclaredMethod("size");
        size.setAccessible(true);
        return (int) size.invoke(mObservers);
    } catch (Exception e) {
        return -1;
    }
}
 
Example #12
Source File: NoteRepository.java    From RoomDb-Sample with Apache License 2.0 5 votes vote down vote up
public void deleteTask(final int id) {
    final LiveData<Note> task = getTask(id);
    if(task != null) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                noteDatabase.daoAccess().deleteTask(task.getValue());
                return null;
            }
        }.execute();
    }
}
 
Example #13
Source File: BaseViewModel.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
/**
 * ensure we are in user scope (has saved user - user logged in)
 * should be called when activity / fragment is created
 * @param userConsumer consume user live data which would be observed to update UI
 * @param onError will be run if user data isn't exist
 *               (show no login button, or navigate user to login page...)
 */
public void ensureInUserScope(PlainConsumer<LiveData<User>> userConsumer, PlainAction onError) {
    if (userManager.checkForSavedUserAndStartSessionIfHas()) {
        userConsumer.accept(userManager.getUserRepo().getUserLiveData());
    } else {
        onError.run();
    }
}
 
Example #14
Source File: BaseRepository.java    From OmniList with GNU Affero General Public License v3.0 4 votes vote down vote up
public LiveData<Resource<List<T>>> getPage(int index, int pageCount, String orderSQL, Status status, boolean exclude) {
    MutableLiveData<Resource<List<T>>> result = new MutableLiveData<>();
    new NormalAsyncTask<>(result, () -> getStore().getPage(index, pageCount, orderSQL, status, exclude)).execute();
    return result;
}
 
Example #15
Source File: BaseRepository.java    From OmniList with GNU Affero General Public License v3.0 4 votes vote down vote up
public LiveData<Resource<T>> get(long code) {
    MutableLiveData<Resource<T>> result = new MutableLiveData<>();
    new NormalAsyncTask<>(result, () -> getStore().get(code)).execute();
    return result;
}
 
Example #16
Source File: ProfileViewModel.java    From triviums with MIT License 4 votes vote down vote up
public LiveData<List<DocumentSnapshot>> getLiveData() {
    if(liveData == null)
        liveData = repository.getProgress();
    return liveData;
}
 
Example #17
Source File: GasSettingsViewModel.java    From trust-wallet-android-source with GNU General Public License v3.0 4 votes vote down vote up
public LiveData<NetworkInfo> defaultNetwork() {
    return defaultNetwork;
}
 
Example #18
Source File: PersonDAO.java    From kripton with Apache License 2.0 4 votes vote down vote up
@BindSqlSelect(where="birthDate=${birthDay}")
LiveData<List<Person>> select(@BindSqlParam(adapter=DateAdapter.class) Date birthDay);
 
Example #19
Source File: BaseViewModel.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
public LiveData<Integer> queueProgress()
{
	return queueCompletion;
}
 
Example #20
Source File: Erc20DetailViewModel.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
public LiveData<Token> token() {
    return token;
}
 
Example #21
Source File: SellTicketModel.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
public LiveData<Wallet> defaultWallet() {
    return defaultWallet;
}
 
Example #22
Source File: BookDao.java    From kripton with Apache License 2.0 4 votes vote down vote up
@BindSqlSelect(jql="SELECT * FROM Book " +
        "INNER JOIN Loan ON Loan.bookId LIKE Book.id " +
        "WHERE Loan.userId LIKE :userId " +
        "AND Loan.endTime > :after "
)
LiveData<List<Book>> findBooksBorrowedByUserAfter(String userId, @BindSqlParam(adapter= DateTime2LongTypeAdapter.class) Date after);
 
Example #23
Source File: BackupKeyViewModel.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
public LiveData<Boolean> deleted() {
    return deleted;
}
 
Example #24
Source File: LoanDaoImpl.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * <h2>Live data</h2>
 * <p>This method open a connection internally.</p>
 *
 * <h2>Select SQL:</h2>
 *
 * <pre>SELECT loan.id, book.title as title, user.name as name, loan.start_time, loan.end_time FROM book INNER JOIN loan ON loan.book_id = book.id INNER JOIN user on user.id = loan.user_id WHERE user.name LIKE :userName AND loan.end_time > :after </pre>
 *
 * <h2>Mapped class:</h2>
 * {@link LoanWithUserAndBook}
 *
 * <h2>Projected columns:</h2>
 * <dl>
 * 	<dt>id</dt><dd>is associated to bean's property <strong>id</strong></dd>
 * 	<dt>title</dt><dd>is associated to bean's property <strong>bookTitle</strong></dd>
 * 	<dt>name</dt><dd>is associated to bean's property <strong>userName</strong></dd>
 * 	<dt>start_time</dt><dd>is associated to bean's property <strong>startTime</strong></dd>
 * 	<dt>end_time</dt><dd>is associated to bean's property <strong>endTime</strong></dd>
 * </dl>
 *
 * <h2>Query's parameters:</h2>
 * <dl>
 * 	<dt>:userName</dt><dd>is binded to method's parameter <strong>userName</strong></dd>
 * 	<dt>:after</dt><dd>is binded to method's parameter <strong>after</strong></dd>
 * </dl>
 *
 * @param userName
 * 	is binded to <code>:userName</code>
 * @param after
 * 	is binded to <code>:after</code>
 * @return collection of bean or empty collection.
 */
@Override
public LiveData<List<LoanWithUserAndBook>> findLoansByNameAfter(final String userName,
    final Date after) {
  // common part generation - BEGIN
  // common part generation - END
  final KriptonLiveDataHandlerImpl<List<LoanWithUserAndBook>> builder=new KriptonLiveDataHandlerImpl<List<LoanWithUserAndBook>>() {
    @Override
    protected List<LoanWithUserAndBook> compute() {
      return BindAppDataSource.getInstance().executeBatch(new BindAppDataSource.Batch<List<LoanWithUserAndBook>>() {
        @Override
        public List<LoanWithUserAndBook> onExecute(BindAppDaoFactory daoFactory) {
          return daoFactory.getLoanDao().findLoansByNameAfterForLiveData(userName, after);
        }
      });
    }
  };
  registryLiveData(builder);
  return builder.getLiveData();
}
 
Example #25
Source File: BookDao.java    From kripton with Apache License 2.0 4 votes vote down vote up
@BindSqlSelect(jql="SELECT * FROM Book " +
        "INNER JOIN Loan ON Loan.bookId LIKE Book.id " +
        "WHERE Loan.userId LIKE :userId "
)
LiveData<List<Book>> findBooksBorrowedByUser(String userId);
 
Example #26
Source File: DetailViewModel.java    From ActivityDiary with GNU General Public License v3.0 4 votes vote down vote up
public LiveData<DiaryActivity> currentActivity() {
    return mCurrentActivity;
}
 
Example #27
Source File: BookDaoImpl.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * <h2>Live data</h2>
 * <p>This method open a connection internally.</p>
 *
 * <h2>Select SQL:</h2>
 *
 * <pre>SELECT * FROM book INNER JOIN loan ON loan.book_id = book.id INNER JOIN user on user.id = loan.user_id WHERE user.name LIKE :userName AND loan.end_time > :after </pre>
 *
 * <h2>Mapped class:</h2>
 * {@link Book}
 *
 * <h2>Projected columns:</h2>
 * <dl>
 * 	<dt>id</dt><dd>is associated to bean's property <strong>id</strong></dd>
 * 	<dt>title</dt><dd>is associated to bean's property <strong>title</strong></dd>
 * </dl>
 *
 * <h2>Query's parameters:</h2>
 * <dl>
 * 	<dt>:userName</dt><dd>is binded to method's parameter <strong>userName</strong></dd>
 * 	<dt>:after</dt><dd>is binded to method's parameter <strong>after</strong></dd>
 * </dl>
 *
 * @param userName
 * 	is binded to <code>:userName</code>
 * @param after
 * 	is binded to <code>:after</code>
 * @return collection of bean or empty collection.
 */
@Override
public LiveData<List<Book>> findBooksBorrowedByNameAfter(final String userName,
    final Date after) {
  // common part generation - BEGIN
  // common part generation - END
  final KriptonLiveDataHandlerImpl<List<Book>> builder=new KriptonLiveDataHandlerImpl<List<Book>>() {
    @Override
    protected List<Book> compute() {
      return BindAppDataSource.getInstance().executeBatch(new BindAppDataSource.Batch<List<Book>>() {
        @Override
        public List<Book> onExecute(BindAppDaoFactory daoFactory) {
          return daoFactory.getBookDao().findBooksBorrowedByNameAfterForLiveData(userName, after);
        }
      });
    }
  };
  registryLiveData(builder);
  return builder.getLiveData();
}
 
Example #28
Source File: DirectorDao.java    From kripton with Apache License 2.0 4 votes vote down vote up
@BindSqlSelect(orderBy = "fullName ASC")
LiveData<List<Director>> getAllDirectors();
 
Example #29
Source File: WalletsViewModel.java    From ETHWallet with GNU General Public License v3.0 4 votes vote down vote up
public LiveData<Wallet> defaultWallet() {
	return defaultWallet;
}
 
Example #30
Source File: LoanDao.java    From kripton with Apache License 2.0 4 votes vote down vote up
@BindContentProviderEntry(path = "loadAll")
@BindSqlSelect
LiveData<List<Loan>> findAllLoans();