Difference between OneTimeWorkRequest.Builder and OneTimeWorkRequestBuilder? - android

I am going through the Google Codelabs Android basics for Kotlin WorkManager. I've seen the code written one way, then later on see it a different way, and was wondering if there was a difference at all between these?
// Add WorkRequest to save the image to the filesystem
val save = OneTimeWorkRequest.Builder(SaveImageToFileWorker::class.java).build()
// Add WorkRequest to save the image to the filesystem
val save = OneTimeWorkRequestBuilder<SaveImageToFileWorker>()
.build()
Do these do the same thing?

OneTimeWorkRequestBuilder<T>() is just a function that creates and returns an object of type OneTimeWorkRequest.Builder and there are no differences between them.
You can check the OneTimeWorkRequestBuilder function signuature here.

Related

Private setter vs Backing Property in Kotlin

I'm an old Java fan and trying to understand Kotlin basics. Can someone tell me what is the difference between these codes:
private val _users = mutableListOf<User>()
val users: List<User>
get() = _users
VS
var _users: mutableListOf<User>()
private set
As far as understand, upper code provides set _users only in that class and get it publicly which seems pretty same with the code below but in Google docs they say it's backing property which i don't get what it is.
Both examples are really totally different. You need to understand the difference between:
val MutableList
and:
var List
First makes possible to modify the contents of a list, but you can't replace the list object itself. Second, you can replace the list object, but you cannot modify its contents. This isn't really specific to Kotlin, it is the same in Java. val (or making a setter private) is like final field and List is like wrapping a list with Collections.unmodifiableList() - they're different things.
In your first example, neither the external nor internal code can replace the list, but internal code can modify its contents - external can't. In second example both internal and external code can modify contents of the list, but only internal code can replace the list entirely.

Deep copy Realm object in Kotlin

I wanna duplicate realm object and then change the second, without reassigning all the keys. How can I do this? RealmObject does not have .copy() or .clone() methods.
// Money is not data class and has ∞ fields which will be boring to re-assign
val money = Money()
money.amount = 1000
...
val anotherMoney = money
anotherMoney.amount = 500
println(money.amount) // prints 500
can you please provide more context and appropriate information as I do not see and array's in your code statement. Thank you.
EDIT
Because Money is not a data class, you do not have the auto-generated copy() function available, that leaves you with two options:
Create an custom copy() function in the Money class. This could be mundane if there are huge amount of fields in the class.
Use 3rd party libraries, in which case you'll add external dependency to your RealmObject.
What I will suggest is a no brainer: Try to convert your Money.class to a Data class. You will get auto generated functions and idiomatically it will work as RealmObjects should be key-values pairs.
EDIT
You can use GSON library's serialization/deserialization and hack your way to solve your problem (although this is a hacky way but will do its job):
fun clone(): Money {
val stringMoney = Gson().toJson(this, Money::class.java)
return Gson().fromJson<Money>(stringMoney, Money::class.java)
}
usage:
val originalMoney = Money()
val moneyClone = originalMoney.clone()

LiveData confusion in [Android] Plaid App

I am referring to the Plaid open source project on github Link to Plaid
It is an excellent source to learn new techniques on Android.
As I was going through the code, I came across a certain style of coding around LiveData which I really didn't understand. If anybody can help me get it.
Here goes:
There's a ViewModel(vm) with this piece of code:
private val _openLink = MutableLiveData<Event<String>>()
val openLink: LiveData<Event<String>>
get() = _openLink
Fairly simple? Note that, there are 2 variables here: openLink and _openLink. The getter for openLink is returning the _openLink LiveData.
In the activity they observe the openLink LiveData as follows:
viewModel.also { vm ->
vm.openLink.observe(this, EventObserver { openLink(it) })
..... // Other stuff
}
Now, the other livedata _openLink is being called by the UI supposedly on a button click and it's defined like this:
fun viewShotRequested() {
_shotUiModel.value?.let { model -> // ignore this part
_openLink.value = Event(model.url) // setValue on _openLink
}
}
So here my understanding is, on setValue() on _openLink, EventObserver{openLink(it)} will get called.
My question is, why have they done it like this?
Questions:
Why not observe directly on _openLink?
Will it not have the same effect? What am I missing here?
_openLink is mutable. You must always expose something which is immutable and cannot be changed by your observer, because that should only be done by your ViewModel, even though exposing _openLink would have no effect.
That's why you need to expose openLink which is immutable.
private val _openLink = MutableLiveData<Event<String>>()
val openLink: LiveData<Event<String>> = _openLink
The MutableLiveData property shouldn't be exposed: it is mutable and could be changed anywhere across your program.
That's why the LiveData is exposed instead: it is responsible for updating your property, and it uses the MutableLiveData as a backing field.
The exception to this would be two-way DataBinding, where direct access to the value would be needed.
My question is, why have they done it like this?
Because Google apparently enjoys writing more code for the sake of writing more code.
The supposed answer if you're inclined to believe them is that LiveData<Event<T>> is preferred over SingleLiveData because they came up with it later than with LiveData<Event<T>> and is therefore supposedly better.
They intend to use an "enqueueable event-bus that forgets items after it is emitted to at least 1 observer", but Jetpack offers no such concept out of the box, personally I had to write one of my own.
Even so, there's a distinction between whether you can write into something, and whether you can only read from something but not write into it yourself. In this case, only the ViewModel wants to be able to emit events, so it is the ViewModel that holds a Mutable__ reference, but exposes a regular LiveData to the outside world (in my case, EventEmitter vs EventSource).
As for the _, it's a Kotlin style convention that will hopefully be changed one day, as you could either do:
private val _openLink = MutableLiveData<Event<String>>()
val openLink: LiveData<Event<String>>
get() = _openLink
But you could also do
private val openLink = MutableLiveData<Event<String>>()
fun openLink(): LiveData<Event<String>> = openLink
And that way we could ditch the _ prefix in our own code, but for some reason the authors of Kotlin hadn't come up with that convention in time.

Is there, in kotlin and android, something similar to switchmap in rxjs or rxjava?

I want to find out is there something similar to switchmap in kotlin and android (LiveData maybe).
I need to change my request immediately after events that can happen very often and which determine what to request from the server, respectively, I only need the last request
In Kotlin you can use the Transformations library as follows
val someLiveData: LiveData<Type> = ...
val someOtherValue = Transformations.switchMap(someLiveData) { changedValue: Type ->
//Assign someOtherValue using changedValue, the value coming from someLiveData.
}

Am I having Kotlin functions return a List correctly?

I am new to Kotlin (coming from Delphi, which is object-oriented Pascal). I just want to ensure I am having functions return List<>s correctly:
Making up an absurdly simple example here:
fun firstTenInts(): List<Int> {
val iList: MutableList<Int> = mutableListOf()
for (i in 1..10)
iList.add(i)
return iList
}
So, my thoughts/questions here are:
Am I correct to use a MutableList within the function and simply return it (even though the function's type is List)?
Do I need to create a local MutableList variable? Do I need any local "list" variable? I am used to (again, Delphi) doing something like:
function firstTenInts: TStringList;
var
i: integer;
begin
result.Clear;
for i := 1 to 10 do
result.Add(IntToStr(i));
end;
which requires no "new" local variable. I simply "work" result which is very similar to Kotlin's return value except that it serves as a local variable of the function's type which can be "worked" throughout the function.
Is there no way to manipulate a Kotlin function's return value other than with another (locally created) variable?
Finally, I can rest assured that any local variables I create are destroyed when the function ends even though I'm "passing them back" - correct?
P.S. I know this is an absurd way to create a List of 10 integers. I am using this only as a framework for the questions/issues I have detailed above. Assume that the returned List will be of unknown size.
(Please do not suggest better ways of creating this list of integers; that is not what I am asking about).
Am I correct to use a MutableList within the function and simply return it (even though the function's type is List)?
Generally that's ok. You do such things if you require a list that can be mutated within the function but from outside you do not want it to be easily mutable (which doesn't mean that it isn't mutable; you could still cast it to a mutable list, i.e. firstTenInts() as MutableList would work and so you could also mutate it again).
Whether you need that mutable list in the function or not actually depends on you. For example just calling listOf(1, 2, 3) will return you a List<Int> immediately, i.e. fun first3Ints() = listOf(1,2,3) will immediately return a List<Int>.
Do I need to create a local MutableList variable? Do I need any local "list" variable? I am used to (again, Delphi) doing something like:
You do not need to, but you can. It's up to you what better suites your needs. This also applies to your local list variable. You do not necessarily need one, even though you will have one nonetheless under the hood. Example:
fun first3Ints() = listOf(1, 2, 3)
translates to something like the following:
fun first3Ints() : List<Int> {
val result = listOf(1, 2, 3)
return result
}
On smaller functions you at least can spare some variable declarations using direct assignments. You can also use something like apply, also, let, run or with to overcome val/var, e.g. (just simulating... all variants can be implemented easier):
fun first3Ints() = arrayListOf().apply {
add(1) // apply allows calling all methods of the receiver directly.. (receiver = arrayListOf...)
add(2)
add(3)
}
fun first2Ints() = arrayListOf().also { // similar to apply, but now there is an 'it' available... you could also name that variable differently, e.g. using .also { result -> result.add(1) }
it.add(1)
it.add(2)
}
Is there no way to manipulate a Kotlin function's return value other than with another (locally created) variable?
So this becomes yes (even though .. technically speaking there will be one)... it is possible, but you need to specify on what you basically want to operate, except for the case where you implement an extension function. Then this within the extension function actually becomes the object you called the function on.
Finally, I can rest assured that any local variables I create are destroyed when the function ends even though I'm "passing them back" - correct?
... yes and no. Yes, you can rest assured that any local variable will be garbage collected when need arises (except you are doing something very special). And there is also the no: you don't know when they will be destroyed. Regarding your returned value it is even more special: you are actually getting only a reference to an object, not the object itself... so somehow you basically get that local variable back. You may want to have a look at JVM / stack and heap and how the objects are referenced and stored...
Your return is right and you can use ArrayList instead of mutableListOf and there will be no problem...
but still I didn't understand your main problem but the main topic you were talking about shows that you want to be sure of using the list as a return and that is right man
There are various ways for creating ArrayList of 10 items (just as an example you given). You can find below code snippet such as example :
// directly returning array list as Kotlin has functionality to define such kind of function just like macros
fun firstTenInts(): List<Int> = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// Or by using standard function apply
fun firstTenInts(): List<Int> = ArrayList<Int>().apply {
for (i in 1..10)
this.add(i)
}
// Or by declaring variable of ArrayList
fun firstTenInts(): List<Int> {
val iList = ArrayList<Int>()
for (i in 1..10)
iList.add(i)
return iList
}
// Or by using standard function with
fun firstTenInts(): List<Int> = with(ArrayList<Int>()) {
for (i in 1..10)
this.add(i)
return#with this
}
Above are the various examples defines how you can do differently (Although sample you provided is also a valid example).

Categories

Resources