Android LiveData - switchMap is not triggered on second update - android

I have a LiveData object that depends on another LiveData. As I understand, Transformations.switchMap should allow to chain them. But switchMap handler is triggered only once and it doesn't react on further updates. If instead I use observe on the first object and, when it's ready, retrieve the second, it works fine but in this case I have to do it in Activity rather than ViewModel. Is it possible to chain LiveData objects, like Transformations.switchMap, but receive all updates, not only the first one?
Here is an attempt to use switchMap:
LiveData<Resource<User>> userLiveData = usersRepository.get();
return Transformations.switchMap(userLiveData, resource -> {
if (resource.status == Status.SUCCESS && resource.data != null) {
return apiService.cartItems("Bearer " + resource.data.token);
} else {
return AbsentLiveData.create();
}
});
Here is an approach with observe in activity (works but requires to keep logic in activity):
viewModel.user().observe(this, x -> {
if (x != null && x.data != null) {
viewModel.items(x.data.token).observe(this, result -> {
// use result
});
}
});

I was trying to do something similar to you. I have a LiveData something, and when that changes I want to query somethingElse from the DB based on a property. Because the property can be null, if I query the DB with it, I'll get an exception. Therefore, if the property is null, I'm returning an empty MutableLiveData.
I have noticed, that when I returned this empty MutableLiveData, the observers that subscribed to somethingElse were not getting any updates. I saw that on your answer you ended up using a MediatorLiveData. Then I steped through my code with the debugger and noticed that the switchMap also uses a MediatorLiveData.
After experimenting a bit, I realised that when creating the empty MutableLiveData, it's initial value is null and won't trigger any updates. If I explicitly set the value, then it will notify the observers.
somethingElse = Transformations.switchMap(something, somethingObject -> {
if (something.someProperty() != null) {
return repository.getSomethingElseByProperty(something.someProperty());
}else{
MutableLiveData<SomethingElse> empty = new MutableLiveData<>();
empty.setValue(null);//need to set a value, to force update of observers
return empty;
}
The code here has worked for me. In the question, you use an AbsentLiveData, which I don't know how it is implemented, so I'm not sure it would work exactly in that case.

As a workaround, I used MediatorLiveData. I add the result of the first call as a source and, when it's ready, replace it with a final call:
MediatorLiveData<MyResponse> result = new MediatorLiveData<>();
LiveData<Resource<User>> source = this.get();
result.addSource(source, resource -> {
if (resource.status == Status.SUCCESS && resource.data != null) {
result.removeSource(source);
result.addSource(apiService.cartItems("Bearer " + resource.data.token), result::postValue);
}
});
return result;

Related

LiveMutableData and copies update to same value?

I have a MutableLiveData variable in my AppRepository which is updated and contains my data. This I have no issues with. I also have the following observable to trigger a UI update with the data it holds in my onCreateView function:
viewModel.projectWithContent.observe(viewLifecycleOwner, {
pwc = it
counterList = it.counterList
})
When I tap either to increase or decrease the counter count and then try to push the update to my Room database, it skips it. I have the following check currently:
if(counterList != null) {
try {
for(counter: Counter in counterList!!) {
if(counter.counter_count != pwc?.counterList!![
pwc?.counterList!!.indexOf(counter)
].counter_count) {
Log.i(LOG_TAG, "Hello")
} else {
Log.i(LOG_TAG, "Goodbye")
}
}
} catch(e: IndexOutOfBoundsException) {
e.printStackTrace()
}
}
It'll always go to Goodbye.
Now. If I put the following just below try
Log.i(LOG_TAG, "PWC: ${pwc?.counterList!![0].counter_count}, " +
"CPWC: ${counterList!![0].counter_count}," +
"VMPWC: ${viewModel.projectWithContent.value?.counterList!![0].counter_count}")
It provides the following output:
PWC: 70, CPWC: 70,VMPWC: 70
Is this a side effect of what I'm doing or?
Thanks
Like #Tenfour04 says, your condition is actually checking they don't match, so "Goodbye" is the output when they do match.
If you don't mind (this is a little long), I just want to recommend some stuff because I feel like you're making life hard for yourself with all the null-checking that's going on - the logic of the code was really hard to read, and I'm guessing that's why you didn't notice the flipped logic too!
First: the ? null safety stuff (and !! which is the opposite of safe, never use it unless you know you have good reason) is there because you have nullable variable types. Normally the IDE would smart cast them to non-null once you've done a null check (like on your first line) - but because they're vars, they can be changed at any time.
That means that a variable that wasn't null before could be now, so you're forced to null-check every single time you access it. But even if the types weren't nullable, because they're vars, they can still change, and the thing you were looking at a moment ago is something different now.
The simple solution is to just make a new variable:
val counters = counterList
if (counters != null) {
...
}
// or if you want to use one of kotlin's scope functions
counterList?.let { counters ->
...
}
Because that new one is a val, it's not going to change what it's pointing at! Once it's null-checked, it's always going to be non-null, so you don't need to use ? anymore.
You have a couple of variables to make - you want to make sure pwc isn't null, and also their counterLists. A quick way to do that is with pwc?.counterList - if pwc is null, it will return null. Otherwise it will move to the next step, and return counterList, which may be null. (Using !! is saying that it definitely never will be null, in which case it shouldn't be nullable at all!)
And you don't actually care about pwc anyway - you're just comparing its counterList to the other, so why don't we pare it back to just those?
val counters = counterList
val pwcCounters = pwc?.counterList
if (counters != null && pwcCounters != null) {
try {
for(counter: Counter in counters) {
if(counter.counter_count != pwcCounters[
pwcCounters.indexOf(counter)
].counter_count) {
Log.i(LOG_TAG, "Hello")
} else {
Log.i(LOG_TAG, "Goodbye")
}
}
} catch(e: IndexOutOfBoundsException) {
e.printStackTrace()
}
}
There's more we could do here, but just by cleaning up those nulls and using the specific variables we want to work with, does that feel easier to read? And more importantly, easier to understand what's happening and what could happen?
Might be worth throwing it in a function too, stops the call site getting cluttered with these temp variables:
fun doThing(counters: List<Counter>?, pwcCounters: List<Counter>?) {
if (counters == null || pwcCounters == null) return
// do the stuff
}
// when you want to do the thing:
doThing(counterList, pwc?.counterList)
So all your null checking is out of the way, your "temp variables" are the fixed parameters passed to the function, it's all nice and neat.
I know this is a long post for such a short bit of code, but it's a good habit to get into - if you're writing code where you're working with nullable vars and you're wrestling with the null safety system, or you keep repeating yourself to access a particular variable nested inside another object, you can make things a lot easier for yourself! You can imagine how wild this could all get for more complex code.
Also if you care, this is how I'd personally write it, if it helps!
fun doThing(counters: List<Counter>?, pwcCounters: List<Counter>?) {
if (counters == null || pwcCounters == null) return
// for (counter in Counters) is fine too I just like this version
counters.forEach { counter ->
// find returns the first item that matches the condition, or null if nothing matches,
// so no need to handle any exceptions, just handle the potential null!
// (this is a really common Kotlin pattern, lots of functions have a "returns null on failure" version)
val pwcCounter = pwcCounters.find { it == counter }
// remember pwcCounter can be null, so we have to use ? to access its count safely.
// If it evaluates to null, the match just fails
if (counter.count == pwcCounter?.count) Log.i(LOG_TAG, "Hello")
else Log.i(LOG_TAG, "Goodbye")
}
}
I also renamed counter_count to just count since it's a property on a Counter anyway. I feel like counter.count is easier to read than counter.counter_count, y'know? It's the little things

How to Listen to more than Three Fields in Observables.combineLatest

I have code to listen to exactly three fields using Observables.combineLatest
Observables.combineLatest(text_name.asObservable(),text_username.asObservable(), text_email.asObservable()).subscribe({ t ->
if (t.first.toString() != currentName || t.second.toString() != currentUsername) {
startActionMode()
} else {
finishActionMode()
}
})
but when I add another parameter to the Observables.combineLatest it throughs error since only 3 inline-parameters can be passed..
Now I would wish to pass 4 parameters in the parameter list for Observables.combineLatest.. I know it should be done using an array or a list, passed in as parameter but It's hard for me to figure it out using Kotlin.
Help me out.. Thanks in Advance..
You need to add a combine function if you want to combine more than 3 observables. You can do something like this.
Observables.combineLatest(
first.asObservable(),
second.asObservable(),
third.asObservable(),
forth.asObservable()
)
// combine function
{ first, second, third, forth->
// verify data and return a boolean
return#subscribe first.toString() != currentName || second.toString() != currentUsername
}
.subscribe({ isValid->
if (isValid) {
startActionMode()
} else {
finishActionMode()
}
})
In the combine function you can verify your data and return a boolean.
Then in subscribe you can take an action based on that boolean

How to remember state with retry operators in RxJava2

I have a network client that is able to resume from interruptions, but needs the last message for doing so when there is a retry.
Example in Kotlin:
fun requestOrResume(last: Message? = null): Flowable<Message> =
Flowable.create({ emitter ->
val connection = if (last != null)
client.start()
else
client.resumeFrom(last.id)
while (!emitter.isDisposed) {
val msg = connection.nextMessage()
emitter.onNext(msg)
}
}, BackpressureStrategy.MISSING)
requestOrResume()
.retryWhen { it.flatMap { Flowable.timer(5, SECONDS) } }
// how to pass the resume data when there is a retry?
Question: as you can see, I need the last received message in order to prepare the resume call. How can I keep track of it so that when there is a retry it is available to make the resume request?
One possible solution may be to create a holder class that just holds a reference to the last message and is updated when a new message is received. This way when there is a retry the last message can be obtained from the holder. Example:
class MsgHolder(var last: Message? = null)
fun request(): Flowable<Message> {
val holder = MsgHolder()
return Flowable.create({ emitter ->
val connection = if (holder.last != null)
client.start()
else
client.resumeFrom(holder.last.id)
while (!emitter.isDisposed) {
val msg = connection.nextMessage()
holder.last = msg // <-- update holder reference
emitter.onNext(msg)
}
}, BackpressureStrategy.MISSING)
}
I think this might work, but it feels like a hack (thread synchronization issues?).
Is there a better way to keep track of the state so it is available for retries?
Note that, unless you rethrow a wrapper around your last element (not too functionally different from your existing "hack"-ish solution but way uglier imo), no error handling operators can recover the last element without some outside help because they only get access to streams of Throwable. Instead, see if the following recursive approach suits your needs:
fun retryWithLast(seed: Flowable<Message>): Flowable<Message> {
val last$ = seed.last().cache();
return seed.onErrorResumeNext {
it.flatMap {
retryWithLast(last$.flatMap {
requestOrResume(it)
})
}
};
}
retryWithLast(requestOrResume());
The biggest distinction is caching the trailing value from the last attempt in an Observable with cache rather than doing so manually in a value. Note also that the recursion in the error handler means retryWithLast will continue to extend the stream if subsequent attempts continue failing.
Take a close look to buffer() operator: link
You could use it like this:
requestOrResume()
.buffer(2)
From now, your Flowable will return List<Message> with two latests objects

RxJava chain to a database and a server

I'm trying to create a good chain. I think this question is popular and has been asked, but I haven't found it.
So what I want is to go to the database and if I don't have anything inside it, I want to download info from the server.
Here is the code:
() -> loadPriceListFromDatabase.call(null)
.flatMap(mealTypes -> {
if (mealTypes.size() != 0 ) {
return Observable.just(mealTypes); //here is the place where I'm not sure about code style.
}
return loadPriceList.call(null)
.map(model -> {
preferences.setPriceListDate(model.getDate().getTime());
return ActiveAndroidHelper.saveMeals(model);
});
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()),
MainActivity::onTestLoaded,
BaseActivity::onError
So how should I do this? Any must use examples?
UPD
I want to put any condition I want inside if\else block.
if (mealTypes.size() != 0 ) {
not only something is null or zero.
For example I can say
if (date == currentDate) { (//where date is timestamp
It's as simple as:
Observable.concat(
databaseObservable.filter(databaseItem -> databaseItem.date == currentDate) ,
networkObservable
).take(1).subscribe(...)
It won't subscribe to the networkObservable unless your databaseObservable completes without onNext.
Use swtichIfEmpty operator, in case your observable is empty automatically you can provide a new one in the pipeline.
Check this example
#Test
public void testSwitchPerson() {
Observable.just(new ArrayList<>())
.flatMap(persons -> Observable.from(persons)
.switchIfEmpty(Observable.just(new Person("new", 0, "no_sex"))))
.subscribe(System.out::println);
}
if you want to see more practical example check here https://github.com/politrons/reactive

How can I base method return value on Subscription?

I have a small code sample that returns some data from api or from database, depending on with one from above contains any data.
Now I want to add another condition based on Network status. I use ReactiveNetwork library for this but I can't make it work, this is what I tried:
#Override public Observable<List<Tactic>> getTactics(boolean forceRefresh) {
Observable<List<Tactic>> diskObservable =
disk.get().getTactics().compose(RxDataUtils.applyLog(SourceType.DISK));
Observable<List<Tactic>> apiObservable = api.get()
.getTactics()
.doOnNext(tactics -> disk.get().save(tactics))
.compose(RxDataUtils.applyLog(SourceType.API));
Subscription connectivityStatusSubscription = new ReactiveNetwork().observeConnectivity(context)
.compose(RxUtils.applyStandardSchedulers())
.subscribe(connectivityStatus -> {
isNetworkAvailable = RxDataUtils.isConnected(connectivityStatus);
Timber.v("ConnectivityChanged: " + isNetworkAvailable);
});
if (isNetworkAvailable) return forceRefresh ?
apiObservable : Observable.concat(diskObservable, apiObservable).first(
tactics -> (tactics != null && tactics.size() > 0));
return diskObservable;
}
It didn't log anything at all
You should be combining the status stream with the others, not creating two separate subscriptions - otherwise it doesn't really react to the network connectivity.
What you probably want to use is switchMap. Every time the network connectivity changes it can update which stream you're using.
In broad strokes, it'd go something like this:
connectivityObservable.switchMap(isConnected -> {
if (isConnected) {
return networkObservable;
}
return diskObservable;
}
(It looks like yours would be a bit more complex, I just want to lay out the general idea here.)

Categories

Resources