https://kotlinlang.org logo
#android
Title
# android
s

Shan

09/26/2019, 7:55 PM
Has anyone implemented a Kotlin solution to creating non-nullable LiveData types? Trying to think of the best way to do this.. Right now I have an extension function which will get the value only if it's not null, otherwise throw (as the value should never be null), but I'd much rather do it as a functionality of the setter and force the LiveData to have an initialization value as well as not being able to set it to null.
1. LiveData has a constructor in its class which will initialize the class with no value passed, which I would like to do away with (without making my own observable.. if anyone has any suggestions) 2. LiveData annotates its
getValue
function with
@Nullable
which I would also like to do away with.
l

louiscad

09/26/2019, 8:07 PM
My solution is to use
Flow
and bridge it to
LiveData
, not exposing
MutableLiveData
, and I observe only notNull values, with an extension (that I can link if you want)
1
s

Shan

09/26/2019, 8:07 PM
Please do! That sounds very promising
I intend to replace my LiveDatas with Data Flows when they are released at some point, hopefully soon!
l

louiscad

09/26/2019, 8:14 PM
I think AndroidX LiveData KTX now has these but I'm not sure. Anyway, here are my extensions: https://github.com/LouisCAD/Splitties/blob/de82f24a60bb92198a120634971c41e86dc72c24/modules/arch-lifecycle/src/androidMain/kotlin/splitties/arch/lifecycle/LiveData.kt#L21 The obsolete API annotations are because I plan to remove overlap with KTX artifacts. To bridge a
Flow
to a
LiveData
, here's what you can do with latest LiveData KTX (should be in stable now):
Copy code
val yourLiveData = liveData {
    myFlow.collect { myData ->
        /*this@liveData.*/emit(myData)
    }
}
s

Shan

09/26/2019, 8:18 PM
LiveData KTX, you mean the third party library? Or is this a part of AndroidX?
Ah, I see it's part of the androidx lifecycle-livedata-ktx library. Very nice! Thanks 👍