How do you 'remember' something which could be nul...
# compose-desktop
v
How do you 'remember' something which could be null (and probably will be initially?). I.E. can you remember a class, but not an instance of it?
var something = remember { mutableStateOf<MyClass>(_* can't construct here because it's currently null *_) }
?
e
I would suggest a sealed class. Therefore you eliminate the use of null all together
b
mutableStateOf<MyClass?>(null)
☝️ 4
v
I don't think a sealed class is going to work; I'm trying to make something very generic. Martynas's suggestion seems to be working.
Though of course, I've hit my next snag...
I don't Compose likes generics very much.
e
Copy code
sealed class State {
   object Loading: State()
   class Ready(val myClass: MyClass): State()
}

// your code
val nullableFoo = ...
var state = remember { mutableStateOf<State>( 
   if (nullableFoo != null) Ready(MyClass(nullableFoo)) else Loading
)}

when (state) {
   is Loading -> // show loading component
   is Ready -> state.myClass.... // show some component with state.myClass
}
a sealed class should work with generics. its commonly used with like Results
Copy code
sealed class Result<out T : Any> {
    data class Success<out T : Any>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}
b
sealed class Nullable<T>(val value:T) { abstract val isPresent: Boolean object Null: Nullable<Never>(null) { override val isPresent = false } class Present<T>(value: T): Nullable(value) { override val isPresent = true } }
v
Thanks, I'll take a look. I'm at that stage where I've got about 12 possible solutions and need to step back and think!
b
mutableStateOf<Nullable<MyType>>(Nullable.Null)
Although I prefer nullable MyClass? type over this
v
For now I've done
Copy code
mutableStateOf<FontModel?>(null)
👍 3
Have you ever worked with fonts? Confusing things. I've got 3 different import aliases to distinguish between different
Font
classes (and a Compose function called
Font
).