Make Android Lifecycle Observer receiver non nullable in Kotlin - android

I have Result wrapper that wraps data comes from backend
data class Result<T>(val success: Boolean, val result: T?, val message: String?)
Idea of this, check success instead of result being null or not valid and get formatted message for UI error reporting. But when trying to use this with android lifestyle components, specifically in Observer I have to check for null.
How can I avoid this null check? This happens because of
void onChanged(#Nullable T t);
in Observer. I've tried to extend this but it seem to require more custom wrapper classes. Do we have a solution for avoid null check here.

It's a framework bug that argument is annotated as #Nullable. Fixed in androix.lifecycle 2.0.0-beta01.

Updated answer from #Andrei Vinogradov's answer
Until you upgrade to 2.0.0-beta01, you can try this solution. Use standard function let from Kotlin library :
it?.let{ result ->
if(result.success){
// Rest of your code ..
}
}

Related

Kotlin - Issue Extending Kotlin String Class

I am currently trying to extend Kotlins String class with a method in a file StringExt.kt
fun String.removeNonAlphanumeric(s: String) = s.replace([^a-ZA-Z0-9].Regex(), "")
But Kotlin in not allowing me to use this method in a lambda:
s.split("\\s+".Regex())
.map(String::removeNonAlphanumeric)
.toList()
The error is:
Required: (TypeVariable(T)) -> TypeVariable(R)
Found: KFunction2<String,String,String>
What confuses me about this is that Kotlins Strings.kt has very similar methods and
I can call them by reference without Intellij raising this kind of issue. Any advice is appreciated.
This is because you have declared an extension function that accepts an additional parameter and should be used as s.replace("abc").
I think what you meant is the following:
fun String.removeNonAlphanumeric(): String = this.replace("[^a-ZA-Z0-9]".toRegex(), "")
This declaration doesn't have an extra parameter and uses this to refer to the String instance it is called on.
I thing this is because a lambda is an anonymous function and dose not access to the scope of a extension file.
Check this link maybe contains some useful information:
https://kotlinlang.org/docs/reference/extensions.html

Managing Data With Coroutines

In my android project I have tried to implement a shared View Model which does all the reading and writing data. I do this by using Mutable Live Data and my activity calls an update function within the View Model to update the Live Data. However I can't figure out how to get the data after it has been accessed. It seems that I am trying to update my UI before the data gets accessed. I have looked up this problem and it seems the solution has something to do with coroutines. I have not been successful implementing coroutines and I always get a null value for my data.
ViewModel :
private val firebaseDatabase: DatabaseReference = FirebaseDatabase.getInstance().reference
private val fAuth = FirebaseAuth.getInstance()
private val user: FirebaseUser = fAuth.currentUser!!
private var _saveLocation: MutableLiveData<LocationEvent> = MutableLiveData<LocationEvent>()
val saveLocation: LiveData<LocationEvent> get() = _saveLocation
fun loadData() {
firebaseDatabase.child("User").child(user.uid).child("SaveLocation").get()
.addOnSuccessListener {
_saveLocation.value = LocationEvent(
it.child("title").getValue<String>()!!,
it.child("organizer").getValue<String>()!!,
LatLng(
it.child("locationLatLng").child("latitude").value as Double,
it.child("locationLatLng").child("longitude").value as Double
),
it.child("address").getValue<String>()!!,
it.child("description").value as String,
it.child("allDay").value as Boolean,
it.child("sdate").getValue<Calendar>()!!,
it.child("edate").getValue<Calendar>()!!,
it.child("notifications").getValue<MutableList<Int>>()!!,
user.uid
)
}.addOnFailureListener {}
}
Activity function :
private fun loadSaveData() {
dataViewModel.loadData()
//using log statement just to see if any value
//Always get null
Log.d("MainFragment", "${dataViewModel.saveLocation.value}")
}
I did not include any attempt at coroutines above.
Question
How can I use coroutines to fix this problem?
If not coroutines than what?
(Side Question) : Why does casting to type Calendar cause a crash?
Any help whether its a solution or pointing me to a solution would be much appreciated.
Whenever you use code with names like "add listener" or "set listener" or ones with words like "fetch" or "async" in the name and take lambda parameters, you are calling an asynchronous function. This means the function returns before it finishes (and usually before it even starts) doing what you requested it to.
The purpose of the listener/callback/lambda function you pass to it is to do something sometime in the future, whenever the work eventually is completed. It could only be a few milliseconds in the future, but it absolutely will not happen until after your other code under the function call is complete.
In this case, your get() call to Firebase is synchronous, and you are adding a listener to it to tell it what to do with the results, when they eventually arrive. Then your flow of code continues on synchronously. Back in your loadSaveData() function, you are checking for the results, but the request and your listener have not been completed yet.
You don't need coroutines to get around this. Coroutines are a convenient syntax for dealing with code that normally uses callbacks, but regardless of whether you use coroutines, you need to understand what is going on. IO operations like what you're using cannot be done on the main thread, which is why they are done synchronously.
There's a lot more info about this in this StackOverflow question.

Kotlin sytax for '?' constant issue

I must be doing something wrong with Kotlin implementation of view models
I have a view model that has a function to retrieve youtube video id from url.
fun getYoutubeVideoId(url: String): String?{
return "([a-zA-Z0-9_-]{11})".toRegex().find(url)?.value
}
I feel like I'm always in catch 22 because I use this function in a fragment inside with LiveData observable, which forces me to to ? on objects, which then forces me to have return type with ?, which then tirggers if statements to check if objects aren't null.
Here is the vm var
val streamUrl= mainState.getOrNull { it?.account?.streamUrl ?: 0}.distinctUntilChanged()
Here is my shortened observable
streamUrl.observe{
playVideo(getYoutubeVideoId(it))
}
The error from above statement is that it
Requires a String and I'm passing Any
Return should be String and its String?
I'm running around to make sure the types match and its always something not matching or being right. I think I could setup another streamUrl variable under the viewModel besides the observable, but I feel like I should be able to just do it of a single variable.
I hope this makes sense.
So the first thing to embrace with kotlin is: Null Safety.
Null Safety does not mean that you do not get nulls.
It means, that if something is possibly null, the compiler forces you to think about it and handle it at a point that makes sense. If you don't, you potentially get the notorious NullPointerException at an unexpected and possibly ugly point of execution.
So, to eliminate the ? think about where you want to handle the possibility of it being null -> check it -> handle it in an elegant way, and then safely pass the checked result without a ? to the rest of your code.

How to make IDE to understand that, the object exactly not null after method call

I am using android studio with Kotlin language
and when I call the function above, its warning to check null state of "obj"
How its possible to make IDE (Android Studio) to understand that after some method call, the (passed) object exactly not null... thanks
Instead of an opaque isNotNull method call, which Kotlin can't (and shouldn't) reason about, use one of the idioms native to the language, such as:
value?.let {
val response = it.response
...
}

Lifecycle methods in statically typed languages

In the last year I've become a mobile developer and a functional programming admirer.
In each of the mobile arenas there are components with lifecycle methods that make up the meat of the app. The following will use Android and Kotlin as examples, but the same applies to iOS and Swift.
In Android, there are Activity's with lifecycle methods like onCreate(). You might also define a function, onButtonClicked(), which will do exactly what the name describes.
For the purposes of the question, let's say there's a variable defined in onCreate() that is used in a button click handler onButtonClickedPrintMessageLength() (This is usually the case - onCreate() is essentially Activity's setup method).
The example class would look like this:
class ExampleActivity: Activity() {
var savedStateMessage: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedStateMessage = "Hello World!"
}
fun onButtonClickedPrintMessageLength() {
System.out.println(savedStateMessage?.length)
}
}
Notice the declaration of savedStateMessage as a String? (nullable string) and the use of ?. (null safe call). These are required because the compiler cant guarantee that onCreate() will be called before onButtonClickedPrintMessageLength(). As developers though, we know that onCreate will always be called first* **.
My question is how can I tell the compiler about the guaranteed order of these methods and eliminate the null checking behavior?
* I suppose it's possible to new up our ExampleActivity and call onButtonClickedPrintMessageLength() directly, thus sidestepping the Android framework and lifecycle methods, but the compiler/JVM would likely run into an error before anything interesting happened.
** The guarantee that onCreate is called first is provided by the Android framework, which is an external source of truth and might break/function differently in the future. Seeing that all Android apps are based on this source of truth though, I believe it's safe to trust.
Although this won't answer your actual question, in Kotlin you can use lateinit to tell the compiler that you'll initialize a var at a later point in time:
lateinit var savedStateMessage: String
You'll get a very specific UninitializedPropertyAccessException if you try to use this variable before initializing it. This feature is useful in use cases like JUnit, where you'd usually initialize variables in #Before-annotated method, and Android Activitys, where you don't have access to the constructor and initialize stuff in onCreate().
As mentioned in another answer, lateinit is available as an option to defer initialization to a later point in a guaranteed lifecycle. An alternative is to use a delegate:
var savedStateMessage: String by Delegates.notNull()
Which is equivalent, in that it will report an error if you access the variable before initializing it.
In Swift this is where you would use an implicitly-unwrapped Optional:
class Example: CustomStringConvertible {
var savedStateMessage: String! // implicitly-unwrapped Optional<String>
var description: String { return savedStateMessage }
init() {
savedStateMessage = "Hello World!"
}
}
print(Example()) // => "Hello World!\n"
By using the operator ! at the end of String in the second line of the example you are promising that the variable will be set before it can be used. This is accomplished in the init method of the example. It's still an Optional but code can treat it as a String since it will be automatically unwrapped before each use. You must take care that the variable is never set to nil when it might be accessed or a runtime exception may be generated.

Categories

Resources