Get the updated value first in AtomicBoolean

299 views Asked by At

getAndSet returns the "previous" value then set the updated value, I want the "reverse" behavior, to return the updated value and then set it in the AtomicBoolean object. just like when you do

if(bolVal = otherBolVal)

the assignment here precedes the evaluation. can it be done with AtomicBoolean alone or do I need a custom class which is not good for me.

I had this

sharedPref.edit().putBoolean("tag", isOvertime = false).apply();

which was done in one line, now I was forced to pass the boolean as a mutable object so I didn't want to create a custom class and went for AtomicBoolean. now I'm looking for a way to do the same one line assignment with least efforts without creating a new class or an extra line expression.

2

There are 2 answers

5
magicmn On BEST ANSWER

Something like this?

private final AtomicBoolean atomicBoolean = new AtomicBoolean();

public boolean setAndGet(boolean bool) {
    atomicBoolean.getAndSet(bool);
    return bool;
}

Nope you will need a custom class that extends AtomicBoolean or a Utils class. There is no reason to have a method for this in AtomicBoolean. Even in your case it's just one more line of code...

0
Alireza Jamali On

I figured it out as a one liner solution I was looking, but I don't know if I'm going the right way at all.

in situations where I need to both assign and return true I use:

sharedPref.edit().putBoolean("tag", at.getAndSet(true) || true).apply();

and in situations where I need to both assign and return false I use:

sharedPref.edit().putBoolean("tag", at.getAndSet(false) && false).apply();

I don't have situations where I don't know the new value or update value but in that case:

sharedPref.edit().putBoolean("tag", newVal ? (at.getAndSet(newVal) || newVal) : (at.getAndSet(newVal) && newVal)).apply();

I know its a disaster specially the last one but its the best thing I could come up with.