0

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.

Alireza Jamali
  • 302
  • 2
  • 6
  • 17
  • Why should `getAndSet` return the *new* value? You **know** the new value, since your code actually passes that value in. Can you describe what code you would write with that behaviour? And why you can't write it with the current one? – Joachim Sauer Mar 06 '20 at 11:27
  • Why would you wand to get the new value? You already have it (you need it to provide it as a parameter to `getAndSet`). – Nicktar Mar 06 '20 at 11:32
  • I want to do 2 things in one expression, both return the new value and assign it to the AtomicBoolean object, both be done inside the argument – Alireza Jamali Mar 06 '20 at 11:42

2 Answers2

2

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...

magicmn
  • 1,787
  • 7
  • 15
0

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.

Alireza Jamali
  • 302
  • 2
  • 6
  • 17