Reputation: 675
The below code working fine so far,
class Controller extends GetxController{
var count = 0.obs;
increment() => count++;
}
But when I assign a value it doesn't work as expected not event with type cast.
class Controller extends GetxController{
var count = 0.obs;
reset() => count = 10;
}
I would like to know how to assign value ( with '=' ) in get x obs objects?
Upvotes: 1
Views: 8620
Reputation: 31219
This answer has been changed after I have been notified that I was wrong. I want to say thanks to Ivo Beckers to pointing put my misunderstanding of how RxInt
works. Please upvote his answer.
0.obs
returns the type RxInt
. When you call ++
on this object, it is calling the +
operator on the RxInt
object with 1
to increment the value. It should be noted that the +
and -
operators for RxInt
does manipulate the object itself and does therefore not behave like e.g. int
which is immutable and does therefore require the return of a new object from the operation.
When you do count = 10
you are actually saying you want count
to be overwritten with 10
which are of the type int
and not RxInt
.
What you want is more likely to be the following to you can report back to any subscribers that the value have been reset to 10
:
class Controller extends GetxController{
var count = 0.obs;
reset() => count.value = 10;
}
Upvotes: 7
Reputation: 23164
To set the value of an RxInt
you simple assign it to the value. So you do
reset() => count.value = 10;
The reason why ++ also works is because count++
simply translates to count = count + 1
and this calls the operator on the RxInt
instance which simply increases its value as you can see in the implementation of RxInt
:
class RxInt extends Rx<int> {
RxInt(int initial) : super(initial);
/// Addition operator.
RxInt operator +(int other) {
value = value + other;
return this;
}
/// Subtraction operator.
RxInt operator -(int other) {
value = value - other;
return this;
}
}
Upvotes: 4