1
votes

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

  1. Requires a String and I'm passing Any
  2. 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.

1
Even though Kotlin allows you to omit types, specifying them explicitly is a good way to debug type errors in Kotlin. - Egor

1 Answers

1
votes

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.