Is there a way, perhaps using RxBinding, to bind an Observable<String> to a TextView object such that its .text property is kept up to date with the Observable? Obviously, you could subscribe() and manually update the text field, but a convenience method seems likely. I just can't find it, and the documentation hasn't yielded any answers for me.
A similar convenience method exists in RxSwift (or rather RxCocoa), in case that clarifies what I am asking for; it's called .bindTo() there.
Yes methods like this is presented in rx-binding library.
For example for TextView RxTextView.text(textView) creates action which can be used as subscriber.
See source code
Usage would be something like this
observable.subscribe(RxTextView.text(textView), Throwable::printStackTrace);
Be careful with memory and read docs:
Warning: The created observable keeps a strong reference to view. Unsubscribe to free this reference.
It is not the same as bindTo magic but doing what you need.
Related
Imagine the following object
data class CourseState(
val key:Int=0,
val name:String="",
val courses:Courses=Courses())
Implementing the following pattern
private val _courseState = mutableStateOf(CourseState())
val courseState: State<CourseState> = _courseState
I can trigger recomposition of my UI by calling:
_courseState.value = CourseState()
but not by calling:
_courseState.value.courses.addCourse(Course("some course))
this is a bit frustrating because even though the object has clearly changed I am forced to create a whole new instance of the parent object in order to elicit a small change in it.
Now, I know than behind the scenes Compose is using the .equals() method in order to acertain if it should recompose the layout so I ve had a few ideas on how to achieve the desired behaviour.
overwrite the equals method: it would imply a bit of boilerplate code and it would have to be done for the entire set of nested classes that make up my object. this might work but seems dangerous and cumbersome.
use a clone method or a constructor that accepts an instance of its own class as a parameter to create an identical copy of my object that would nevertheless represent a new instance that I can modify and then pass as the mutable state value. sounds easier than the previous optoin but elegance is something different
dive deep into the State and MutableState classes and find out if there is a way to make them behave as I want. I am relying on some of you to have done this before so I dont have to XD
Let me know what you think or if there is some other ovbious solution that has just eluded me so far
There are two options I would consider:
As you mention, create new instances of your objects for every change. With data classes and copy, it's quite easy, it will add some overhead though.
Make all the data that you need to change observable. If you only want to observe them from compose, make it State, otherwise you can use Flow or LiveData. I suppose that your Courses class contains some List to which
you are adding items. Make it a
mutableStateListOf(),
whenever you add something there, composables that use it should
recompose automatically.
I have a document on Firestore, from which I read its fields in a fragment. Since it has many fields, I set variables in the Activity that hosts this fragment so that I can pass the data between other fragments. In order to achieve that, I realize that I have to write similar lines of codes over and over again, which got me to thinking if there is a better way.
Two possible solutions that come to my mind:
Structure all these fields in JSON format -> something that wouldn't be suitable in Firestore's document system imo
Put all these fields into a serializable data class which I keep in the activity then pass it around the bundles of fragments -> Seemed to complicated and I would still have to write it.get(foo) as bar for each of the field's of this class' constructor.
Given all these, what is the best approach? Thanks in advance.
You have a several options on how to approach this. There is none that's necessarily better than another. Ultimately, you will pick the one that best suits your needs and preferences.
You can do what you're doing now.
You can go a step further an actually check the types of the values instead of just blindly casting them (which would cause a crash at runtime if they didn't match).
You can provide a Class object to get(String, Class<T>) that can automatically map the fields to properties in a new object of type T, as long as the types also match.
You can call a variety of type-specific versions of get, such as getString()
Ultimately you will have to decide if you are going to trust what you get in the snapshot and allow errors to happen, or trust nothing and check everything. It's up to you.
Before Kotlin, Android developers supposed to save reference to the Activity's Views in a variable like this:
Button fooBtn = (Button) findViewById(R.id.btn_foo)
to reduce the amount of the boiler-plate code and the number of findViewById calls.
With the introduction of the Kotlin's Android Extensions we can reference the same Button by simply using:
btn_foo
Questions:
Does the btn_foo have a reference to the Button saved, or does it call findViewById every time?
Do developers still suppose to use variables to store btn_foo to improve app's performance, or just use it directly in the code?
Edit: there is an explanation how Extensions work, however it is still a bit unclear.
It's cached, so findViewById isn't called every time you need it. Storing the variable won't definitely improve the app's performance
One of the Kotlin Android Extension (KAE) developers Ihor Kucherenko confirmed that:
KAE will keep a reference to the view after the first call, instead of using findViewById all the time. That works only for Activities and Fragments.
KAE will not cache data and will use findViewById every time for any other element (except for an Activity/Fragment).
So in case you are going to init a ViewHolder:
class FooViewHolder(view: View): RecyclerView.ViewHolder(view) {
fun bind(day: FooItem.Day) {
btn_foo.text = day.title
}
}
Decompile into Java call will look like:
((Button)this.itemView.findViewById(R.id.btn_foo)).setText((CharSequence)day.getTitle());
which is exactly what you want to avoid.
The developers might be aware of this.
Conclusion: fill free to use KAE without any additional variables, but only for your Activitiies/Fragments.
I was wondering what the difference between database.getReference("foo/bar/123") and database.getReference("foo").child("bar").child("123") is?
I'm assuming that the later one will load the complete "foo" object whereas database.getReference("foo/bar/123") just loads the "123" object?
Is my assumption correct or what is the correct / most efficient way to only load data of "123"?
The two are equivalent. You can inspect this manually this by printing the toString() format for both References.
References are cheap - there's nothing inefficient about either solution. Neither one has yet loaded any data. A Reference is just a pointer to a location in the database.
It should not make a difference, a reference is not actually accessed when instantiated. This is the most relevant document I can find,
https://firebase.google.com/docs/reference/node/firebase.database.Reference
The docs don't say it explicitly, but requests are only performed when using the .set() or .on() methods
In the source code of Activity.java, I see some methods bellow :
public View findViewById(int id) {
return getWindow().findViewById(id);
}
and the definition of getWindow method:
public Window getWindow() {
return mWindow;
}
But as the following rules:
Avoid Internal Getters/Setters
In native languages like C++ it's
common practice to use getters (e.g. i
= getCount()) instead of accessing the field directly (i = mCount). This is
an excellent habit for C++, because
the compiler can usually inline the
access, and if you need to restrict or
debug field access you can add the
code at any time.
On Android, this is a bad idea.
Virtual method calls are expensive,
much more so than instance field
lookups. It's reasonable to follow
common object-oriented programming
practices and have getters and setters
in the public interface, but within a
class you should always access fields
directly.
Without a JIT, direct field access is
about 3x faster than invoking a
trivial getter. With the JIT (where
direct field access is as cheap as
accessing a local), direct field
access is about 7x faster than
invoking a trivial getter. This is
true in Froyo, but will improve in the
future when the JIT inlines getter
methods.
so I want to know why android developers not access this mWindow object directly? If the JIT of the current android versions cannot inline the access, getWindow().findViewById(id) will costs more time than mWindow.findViewById(id), and findViewById is a rather frequently used method.
First: you can't access it because it's private.
Why is it private?
As you said, accessing members directly is faster. On the other hand, you are invoking a method that isn't very fast as it will lookup for some view in the view hierarchy. So using a method instead of a direct access will incur in a small overhead in terms of percentage of the total time that it would take to perform that task.
Anyway, I believe that the reason for this is encapsulation.
You are invoking something you don't own (that is the Android SDK). So, you shouldn't make any assumptions of whats happening "in the other side". Simply use this method and expect that it will return the view you want (or null if it doesn't exists).
Maybe the next version of android will use a different method to lookup a view, not calling getWindow(). If you use this method, they (Google/Android) can simply mark the method as deprecated and "forward" your invocation to the newest implementation. If you were calling directly getWindow(), maybe you would be looking for something that is no longer placed in there.
You can't access the mWindow property directly - it's private.
And I wouldn't care about the speed of findViewById, since you only need to call it once for every view in your layout in your onCreate() method and store the views in members of your activity. You do call findViewById only once per view, don't you? ;-)
However, if you really care about these things, you could call getWindow() for yourself, store it into a local variable and call findViewById on it directly. I wouldn't recommend this because all your performance increasements here are not worth the time and anyway will be obsolete with future versions of the JIT.
If you do this I would be very interested in the amount of microseconds you saved. :-)
We have a reason to smile now...
The android documentation which says to avoid internal getters and setters will change soon, supposedly progruard was added to Gingerbread platform which does a fine job of inlining accessor's, please refer to "Avoid Internal Getters/Setters" is bad advice and these two SO posts.
https://stackoverflow.com/a/6716573/892055
https://stackoverflow.com/a/4930538/892055