I'm using RxJava and I want to combine 12 different observables using the operator combineLatest.
I saw a function prototype that takes a list of observables and an implementation of FuncN but I'm not sure how to do this, I'm having trouble implementing the call method.
Can someone show me an example?
There is a combineLatest that takes a List of observables. Here's an example on how to use it:
List<Observable<?>> list = Arrays.asList(Observable.just(1), Observable.just("2"));
Observable.combineLatest(list, new FuncN<String>() {
#Override
public String call(Object... args) {
String concat = "";
for (Object value : args) {
if (value instanceof Integer) {
concat += (Integer) value;
} else if (value instanceof String) {
concat += (String) value;
}
}
return concat;
}
});
Yo expand on that answer, I am using it to read multiple characteristics at once, it can be done like so:
connectionObservable
.flatMap((Func1<RxBleConnection, Observable<?>>) rxBleConnection -> {
List<Observable<?>> list1 = Arrays.asList(
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...),
rxBleConnection.readCharacteristic(UUID...));
return Observable.combineLatest(list1, args -> {
Object o = doSomethingWithResults(args);
return o;
});
})
.observeOn(AndroidSchedulers.mainThread())
.doOnUnsubscribe(this::clearConnectionSubscription)
.subscribe(retVal -> {
Log.d(TAG, "result:" + retVal.toString());
Log.w(TAG, "SUCCESS");
triggerDisconnect();
}, MyActivity.this::onReadFailure);
}
Comments if you have suggestions on how to improve this process.
RxKotlin supports upto 9 opertators in parameters in combineLatest() method but to use more than 9 parameters
means to pass unlimited dynamic custom object arraylist you can use it as below:
First Let me give you simple example with only two parameters with
custom data types
val name = Observable.just("MyName")
val age = Observable.just(25)
Observables.combineLatest(name, age) { n, a -> "$n - age:${a}" }
.subscribe({
Log.d("combineLatest", "onNext - ${it}")
})
Now what if i want to pass multiple parameters in combineLatest? Then
your answer is below: (i have used custom data types, so someone's
custom problem can also be solved here)
val myList = arrayOf(Observable.just("MyName"),
Observable.just(2),
Observable.just(3.55),
Observable.just("My Another String"),
Observable.just(5),
Observable.just(6),
Observable.just(7),
Observable.just(8),
Observable.just(9),
Observable.just(10),
Observable.just(11),
Observable.just(12),
Observable.just(13),
Observable.just(14),
Observable.just(15))
Observable.combineLatest(myList, {
val a = it[0] as String
val b = it[1] as Int
val c = it[2] as Float
val d = it[3] as String
val e = it[4] as Int
val f = it[5] as Int
val g = it[6] as Int
val h = it[7] as Int
val i = it[8] as Int
val j = it[9] as Int
val k = it[10] as Int
val l = it[11] as Int
val m = it[12] as Int
"$a - age:${b}" })
.subscribe({
Log.d("combineLatest", "onNext - ${it}")
})
Here is a simple extension function for RxKotlin if you have 10 sources for combineLatest. You can easily create similar functions for more sources or adapt this to work with plain RxJava.
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables
#Suppress("UNCHECKED_CAST", "unused")
inline fun <T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, T8 : Any, T9 : Any, T10 : Any, R : Any> Observables.combineLatest(
source1: Observable<T1>, source2: Observable<T2>,
source3: Observable<T3>, source4: Observable<T4>,
source5: Observable<T5>, source6: Observable<T6>,
source7: Observable<T7>, source8: Observable<T8>,
source9: Observable<T9>, source10: Observable<T10>,
crossinline combineFunction: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) -> R
): Observable<R> =
Observable.combineLatest(arrayOf(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10)) {
combineFunction(
it[0] as T1,
it[1] as T2,
it[2] as T3,
it[3] as T4,
it[4] as T5,
it[5] as T6,
it[6] as T7,
it[7] as T8,
it[8] as T9,
it[9] as T10
)
}
Note: I've created this as an extension function to stay consistent with how combineLatest function calls look like for less than 10 sources (Observables.combineLatest(...)). That way I don't have to think about which combineLatest version I need for what number of parameters. Technically there is no need to make it an extension function.
To expand on Egor Neliuba's answer, you can aggregate all the results inside a container object, and then use it as you will inside the subscribe clause:
List<Observable<?>> list = new ArrayList<>();
list.add(mCreateMarkupFlowManager.getFlowState());
list.add(mCreateIssueFlowStateManager.getIssueFlowState());
list.add(mViewerStateManager.getMarkupLoadingProgressChanges());
list.add(mViewerStateManager.getIssueLoadingProgressChanges());
list.add(mMeasurementFlowStateManager.getFlowState());
list.add(mViewerStateManager.isSheetLoaded());
list.add(mProjectDataManager.isCreateFieldIssueEnabledForCurrentProject().distinctUntilChanged());
list.add(mViewerStateManager.getMarkupViewMode());
list.add(mViewerStateManager.isFirstPerson());
list.add(mProjectDataManager.isCreateRfiEnabledForCurrentProject().distinctUntilChanged());
list.add(mCreateRfiFlowStateManager.getRfiFlowState());
attachSubscription(Observable.combineLatest(list, args -> {
Holder holder = new Holder();
holder.setFirst((String) args[0]);
holder.setSecond((Integer) args[1]);
holder.setThird((Boolean) args[2]);
holder.setFourth((Boolean) args[3]);
holder.setFifth((String) args[4]);
holder.setSixth((Boolean) args[5]);
holder.setSeventh((Boolean) args[6]);
holder.setEighth((Boolean) args[7]);
holder.setNinth((Boolean) args[8]);
holder.setTenth((Boolean) args[9]);
holder.setEleventh((String) args[10]);
return holder;
})
.filter(holder -> Util.isTrue(holder.sixth))
.compose(Util.applySchedulers())
.subscribe(holder -> {
if (isViewAttached()) {
String createMarkupState = holder.first;
Integer createIssueState = holder.second;
boolean markupsLoadingFinished = holder.third;
boolean issuesLoadingFinished = holder.fourth;
boolean loadingFinished = markupsLoadingFinished && issuesLoadingFinished;
String measurementState = holder.fifth;
boolean isMarkupLockMode = holder.eighth;
boolean showCreateMarkupButton = shouldShowCreateMarkupButton();
boolean showCreateMeasureButton = shouldShowMeasureButton();
boolean showCreateFieldIssueButton = holder.seventh;
boolean isFirstPersonEnabled = holder.ninth;
Boolean showCreateRfiButton = holder.tenth;
String rfiFlowState = holder.eleventh;
}
})
);
public class Holder {
public String first;
public Integer second;
public Boolean third;
public Boolean fourth;
public String fifth;
public Boolean sixth;
public Boolean seventh;
public Boolean eighth;
public Boolean ninth;
public Boolean tenth;
public String eleventh;
public void setEleventh(String eleventh) {
this.eleventh = eleventh;
}
public void setFirst(String first) {
this.first = first;
}
public void setSecond(Integer second) {
this.second = second;
}
public void setThird(Boolean third) {
this.third = third;
}
public void setFourth(Boolean fourth) {
this.fourth = fourth;
}
public void setFifth(String fifth) {
this.fifth = fifth;
}
public void setSixth(Boolean sixth) {
this.sixth = sixth;
}
public void setSeventh(Boolean seventh) {
this.seventh = seventh;
}
public void setEighth(Boolean eighth) {
this.eighth = eighth;
}
public void setNinth(Boolean ninth) {
this.ninth = ninth;
}
public void setTenth(Boolean tenth) {
this.tenth = tenth;
}
public Holder() {}
}
Related
I have two DAOs, two Repositories and two POJOs. There is some way to create one Livedata of two? I need it to make single list for Recyclerview.
POJOs are similar objects.
ExpenseRepository:
public class ExpenseRepository {
private ExpenseDao expenseDao;
private LiveData<List<Expense>> allExpenses;
public ExpenseRepository(Application application) {
ExpenseIncomeDatabase database = ExpenseIncomeDatabase.getInstance(application);
expenseDao = database.expenseDao();
allExpenses = expenseDao.getExpensesByDay();
}
public LiveData<List<Expense>> getAllExpensesByDay() {
return allExpenses;
}
IncomeRepository:
public class IncomeRepository {
private IncomeDao incomeDao;
private LiveData<List<Income>> allIncomes;
public IncomeRepository(Application application) {
ExpenseIncomeDatabase database = ExpenseIncomeDatabase.getInstance(application);
incomeDao = database.incomeDao();
allIncomes = incomeDao.getIncomesByDay();
}
public LiveData<List<Income>> getAllIncomesByDay() {
return allIncomes;
}
ExpenseDao:
#Dao
public interface ExpenseDao {
#Query("SELECT * FROM expense_table ORDER BY day")
LiveData<List<Expense>> getExpensesByDay();
IncomeDao:
#Dao
public interface IncomeDao {
#Query("SELECT * FROM income_table ORDER BY day")
LiveData<List<Income>> getIncomesByDay();
DailyViewModel:
public class DailyFragmentViewModel extends AndroidViewModel {
private ExpenseRepository expenseRepository;
private IncomeRepository incomeRepository;
private LiveData<Pair<List<Expense>, List<Income>>> combined;
private ExpenseDao expenseDao;
private IncomeDao incomeDao;
public DailyFragmentViewModel(#NonNull Application application) {
super(application);
expenseRepository = new ExpenseRepository(application);
incomeRepository = new IncomeRepository(application);
combined = new DailyCombinedLiveData(expenseDao.getExpensesByDay(), incomeDao.getIncomesByDay());
}
public LiveData<Pair<List<Expense>, List<Income>>> getExpensesAndIncomes() {
return combined;
}
I assume you want to combine them, yes? You'll need a MediatorLiveData, but the guy saying you now need Object is wrong. What you need is a MediatorLiveData<Pair<List<Expense>, List<Income>>>.
public class CombinedLiveData extends MediatorLiveData<Pair<List<Expense>, List<Income>>> {
private List<Expense> expenses = Collections.emptyList();
private List<Income> incomes = Collections.emptyList();
public CombinedLiveData(LiveData<List<Expense>> ld1, LiveData<List<Income>> ld2) {
setValue(Pair.create(expenses, incomes));
addSource(ld1, expenses -> {
if(expenses != null) {
this.expenses = expenses;
}
setValue(Pair.create(expenses, incomes));
});
addSource(ld2, incomes -> {
if(incomes != null) {
this.incomes = incomes;
}
setValue(Pair.create(expenses, incomes));
});
}
}
You could potentially make this generic and it'd be the implementation of combineLatest for two LiveData using tuples of 2-arity (Pair).
EDIT: like this:
public class CombinedLiveData2<A, B> extends MediatorLiveData<Pair<A, B>> {
private A a;
private B b;
public CombinedLiveData2(LiveData<A> ld1, LiveData<B> ld2) {
setValue(Pair.create(a, b));
addSource(ld1, a -> {
if(a != null) {
this.a = a;
}
setValue(Pair.create(a, b));
});
addSource(ld2, b -> {
if(b != null) {
this.b = b;
}
setValue(Pair.create(a, b));
});
}
}
Beware that I lost the ability to set Collections.emptyList() as initial values of A and B with this scenario, and you WILL need to check for nulls when you access the data inside the pair.
EDIT: You can use the library https://github.com/Zhuinden/livedata-combinetuple-kt (Kotlin) or https://github.com/Zhuinden/livedata-combineutil-java/ (Java) which does the same thing.
Created this extension function in kotlin
fun <A, B> LiveData<A>.zipWith(stream: LiveData<B>): LiveData<Pair<A, B>> {
val result = MediatorLiveData<Pair<A, B>>()
result.addSource(this) { a ->
if (a != null && stream.value != null) {
result.value = Pair(a, stream.value!!)
}
}
result.addSource(stream) { b ->
if (b != null && this.value != null) {
result.value = Pair(this.value!!, b)
}
}
return result
}
Instead of having a class to add 2 live datas, another class to add 3 live datas, etc. We can use a more abstract way where we can add as many live datas as we want.
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
/**
* CombinedLiveData is a helper class to combine results from multiple LiveData sources.
* #param liveDatas Variable number of LiveData arguments.
* #param combine Function reference that will be used to combine all LiveData data.
* #param R The type of data returned after combining all LiveData data.
* Usage:
* CombinedLiveData<SomeType>(
* getLiveData1(),
* getLiveData2(),
* ... ,
* getLiveDataN()
* ) { datas: List<Any?> ->
* // Use datas[0], datas[1], ..., datas[N] to return a SomeType value
* }
*/
class CombinedLiveData<R>(vararg liveDatas: LiveData<*>,
private val combine: (datas: List<Any?>) -> R) : MediatorLiveData<R>() {
private val datas: MutableList<Any?> = MutableList(liveDatas.size) { null }
init {
for(i in liveDatas.indices){
super.addSource(liveDatas[i]) {
datas[i] = it
value = combine(datas)
}
}
}
}
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'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
I got tired using this library, this is my first time using it and made a lot of success ways, but i'm a bit confused in getting the following Json :
{
"Guides":
{
"English": {"ArabicSony":"Test1","ArabicNexus":"Test2","ArabicSamsung":"Test3","ArabicHTC":"Test4"}
,"Arabic": {"EnglishSony":"Test1","EnglishNexus":"Test2","EnglishSamsung":"Test3","EnglishHTC":"Test4"}
}
}
Googled and saw a lot of guides and answered, and made my List like this :
public class PostItem {
List<PostItemArabic> Arabic;
List<PostItemEnglish> English;
}
class PostItemArabic{
private String ArabicSony;
private String ArabicNexus;
private String ArabicSamsung;
private String ArabicHTC;
public String getArabicSony() {
return ArabicSony;
}
public void setArabicSony(String arabicSony) {
ArabicSony = arabicSony;
}
public String getArabicNexus() {
return ArabicNexus;
}
public void setArabicNexus(String arabicNexus) {
ArabicNexus = arabicNexus;
}
public String getArabicSamsung() {
return ArabicSamsung;
}
public void setArabicSamsung(String arabicSamsung) {
ArabicSamsung = arabicSamsung;
}
public String getArabicHTC() {
return ArabicHTC;
}
public void setArabicHTC(String arabicHTC) {
ArabicHTC = arabicHTC;
}
}
class PostItemEnglish{
private String EnglishSony;
private String EnglishNexus;
private String EnglishSamsung;
private String EnglishHTC;
public String getEnglishSony() {
return EnglishSony;
}
public void setEnglishSony(String englishSony) {
EnglishSony = englishSony;
}
public String getEnglishNexus() {
return EnglishNexus;
}
public void setEnglishNexus(String englishNexus) {
EnglishNexus = englishNexus;
}
public String getEnglishSamsung() {
return EnglishSamsung;
}
public void setEnglishSamsung(String englishSamsung) {
EnglishSamsung = englishSamsung;
}
public String getEnglishHTC() {
return EnglishHTC;
}
public void setEnglishHTC(String englishHTC) {
EnglishHTC = englishHTC;
}
}
My Model :
private class Model {
private List<PostItem> Guides;
public List<PostItem> getGuides() {
return Guides;
}
public void setGuides(List<PostItem> roms_center) {
this.Guides = roms_center;
}
}
And printing the result like this :
List<PostItem> Guides = response.body().getGuides();
for(int i = 0 ; i < Guides.size() ; i ++ ) {
for (int b = 0; b < Guides.get(i).English.size() ; b++){
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishHTC());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishNexus());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishSamsung());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishSony());
}
for (int b = 0; b < Guides.get(i).Arabic.size() ; b++){
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicHTC());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicNexus());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicSamsung());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicSony());
}
}
My work isn't correct, and getting a lot of errors,
Here's the last error i got :
`Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 3 column 18 path $.Guides
What's the way to make it correct ? `
Based on your models when you try to get the guides list your telling retrofit to populate an array. Retrofit is then getting the data and finding that it is a single object and not array. So you need to update your model to reflect the data returned. For example:
class PostItem {
List<Language> mLanguages;
}
class Language{
String mLanguageTitle; //for example english
List<String> mData; //for this is your list of data
}
Then in your activity instead of getting guides you would get just a post item for example:
response.body().getPostItem();
Hope it helps !
First of all, you can use the retrofit Gson library.
You can handle this in two ways:
Option 1: reformat your languages in your json to be an array like Doug says.
{
"Guides":
[
{"Lang":"English","ArabicSony":"Test1","ArabicNexus":"Test2","ArabicSamsung":"Test3","ArabicHTC":"Test4"}
, {"Lang":"Arabic","EnglishSony":"Test1","EnglishNexus":"Test2","EnglishSamsung":"Test3","EnglishHTC":"Test4"}
]
}
Then you will need to redesign your class to reflect this structure.
Like Doug sayd:
class PostItem {
List<Language> mLanguages;
}
Option 2: Create a custom json desirializer in your class. this will take the Json and break it down into whatever structure you want it to be.
public class PostItem implements JsonDeserializer
#Override
public MyDesirializer deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jarabic = (JsonObject) json.get("Arabic");
//whatever manipulations you want to do (fill with your own code)
PostItem item = new PostItem();
item.arabic = jarabic;
...
...
return item;
}
Trying to understand all that RxJava stuff. I was doing following example:
private Observable<List<String>> query1() {
List<String> urls = new ArrayList<>();
urls.add("1");
urls.add("2");
urls.add("3");
urls.add("4");
return Observable.just(urls);
}
private Observable<List<String>> query2() {
List<String> urls = new ArrayList<>();
urls.add("A");
urls.add("B");
urls.add("C");
urls.add("D");
return Observable.just(urls);
}
and then tried to join two lists:
Observable.zip(
query1(),
query2(),
new Func2<List<String>, List<String>, Observable<String>>() {
#Override
public Observable<String> call(List<String> a1, List<String> a2) {
List<String> list = new ArrayList<>();
list.addAll(a1);
list.addAll(a2);
return Observable.from(list);
}
})
.subscribe(new Action1<String>() { // <-- It says, cannot resolve method subscribe
#Override
public void call(String string) {
String text = testTextView.getText().toString();
testTextView.setText(text + "\n" + string);
}
});
What I'm doing wrong? I was expecting to get in my view
1
2
3
4
A
B
C
D
EDIT1 I ended with the following answer:
Observable.zip(
query1(),
query2(),
new Func2<List<String>, List<String>, List<String>>() {
#Override
public List<String> call(List<String> a1, List<String> a2) {
List<String> list = new ArrayList<>();
list.addAll(a1);
list.addAll(a2);
return list;
}
})
.flatMap(new Func1<List<String>, Observable<String>>() {
#Override
public Observable<String> call(List<String> urls) {
return Observable.from(urls);
}
})
.subscribe(new Action1<String>() {
#Override
public void call(String string) {
String text = testTextView.getText().toString();
testTextView.setText(text + "\n" + string);
}
});
EDIT2 concat solution as suggested by ihuk would be much better in this case. Appreciate for all the answers.
I believe the operators you are looking for are concat or merge.
Concat will emit the emissions from two or more Observables without interleaving them.
Merge on the other hand will combine multiple observables by merging their emissions.
For example:
String[] numbers = {"1", "2", "3", "4"};
String[] letters = {"a", "b", "c", "d"};
Observable<String> query1 = Observable.from(numbers).delay(1, TimeUnit.SECONDS);
Observable<String> query2 = Observable.from(letters);
Observable
.concat(query1, query2)
.subscribe(s -> {
System.out.printf("-%s-" + s);
});
Will print -1--2--3--4--a--b--c--d-. If you replace concat with merge the result will be -a--b--c--d--1--2--3--4-.
Zip operator will combine multiple Observables together via specified function. For example
Observable
.zip(query1, query2, (String n, String l) -> String.format("(%s, %s)", n, l))
.subscribe(s -> {
System.out.printf("-%s-", s);
});
Will output -(1, a)--(2, b)--(3, c)--(4, d)-.
thats because you are trying to return Observable from zip function, but then you pass Action<String>
Observable.zip(
query1(),
query2(),
new Func2<List<String>, List<String>, List<String>>() {
#Override
public List<String> call(List<String> a1, List<String> a2) {
List<String> list = new ArrayList<>();
list.addAll(a1);
list.addAll(a2);
return list;
}
})
.subscribe(
(string)-> System.out.println(string)
);
Observable<List<String>> query1(){
List<String> s = new ArrayList<>();
s.add("1");s.add("1");s.add("1");
return Observable.just(s);
}
Observable<List<String>> query2(){
List<String> s = new ArrayList<>();
s.add("1");s.add("1");s.add("1");
return Observable.just(s);
}
void HelloRx(){
Map<String,String> map2=new LinkedHashMap<>();//pick the result you want to return Here !
Observable.zip(query1(),//Observable Method 1
query2(),//Observable Method 2
(result1,result2)->{
for(String s : result1){//result1 is the value returned by query1 , result2 ...u know.
//do whatever you want
//map.put(......)
}
return null;
})
.subscribeOn(BackgroundSchedulers.getMultiThreadInstance())
.observeOn(AndroidSchedulers.mainThread())
.doOnCompleted(() -> {
//Do Something when finish for example transmit data to your adapter
})
.subscribe();
}
Apparently to join two lists into one list, you can do Observable.concat() on their Observable.from()s and then call Observable.toList().
RealmResults<Cat> equalTo;
RealmResults<Cat> beginsWith;
#Override
public void onViewRestored() {
compositeSubscription = new CompositeSubscription();
equalTo = realm.where(Cat.class).equalTo("field", filterString).findAllSorted("field");
beginsWith = realm.where(Cat.class).beginsWith("field", filterString).findAllSorted("field");
compositeSubscription.add(realm.asObservable()
.switchMap(new Func1<Realm, Observable<Cat>>() {
#Override
public Observable<Cat> call(Realm realm) {
return Observable.concat(Observable.from(equalTo), Observable.from(beginsWith));
}
})
.toList()
.subscribe(cats -> {
// update adapter with List<Cat>
}));