I got placed on a new project at work and it's ref...
# compose-android
c
I got placed on a new project at work and it's refactoring an old android app (that uses) databinding, and migrating to compose. To my surprise, there's no ObservableField extension methods to convert to snapshot state like there is for live data. Am I missing something? Does something like that actually exist and Im just missing it in the docs?
e
I'm pretty sure databinding was deprecated before compose was released so that makes sense.
s
Rip, good luck with that endeavor 🫡
6
🫡 1
m
Fron livedata you can create a stateflow, yes, more code to the work, but sometimes the observable to kotlin flow from the ground Is a better option to make
z
wouldn't it just be something like:
Copy code
@Composable
fun <T> ObservableField<T>.observeAsState(): State<T> {
  val state = remember(this) { mutableStateOf(get()) }
  DisposableEffect(this) {
    val callback: OnPropertyChangedCallback = { _, _ -> state.value = get() }
    addOnPropertyChangedCallback(callback)
    onDispose {
      removeOnPropertyChangedCallback(callback)
    }
  }
  return state
}
☝🏿 1
🙏 1
c
Seems to be close to what I need. currently trying to figure out an error with the return type tho
Return type mismatch: expected 'androidx.compose.runtime.State<T>', actual 'T?'.
z
oops yea that code returned the value not the state, i just fixed it
c
cool. Looks like I just need this return
return state as State<T>
to satisfy the compiler
z
it should already have that type 🤔
unless it's like
out T
or something because java
c
without that it says "Return type mismatch: expected 'androix.compose.runtime.State<T>', actual 'androidx.compose.runtime.MutableState<T?>'
z
oh, i guess the return type should be
State<T?>
since
get()
probably validly returns null if the property isn't initialized? I don't know anything about the contract of
ObservableField
c
oh. lmao. you are correct.
Sorry. should have tried that first.
cool! and yeah. this ObservableField thing is new to me as well. Can't wait to get off of this! appreciate your help (as always) and thanks for teaching!
a
I am confused, as databinding supports conversion to a StateFlow, doesn't that help without additional code? https://developer.android.com/topic/libraries/data-binding/observability#stateflow
c
i would still technically need to convert all of the existing databinding code to stateflow. Long term though we'll likely be going with snapshot state instead of stateflow.
i was wondering if there were any databinding to stateflow extension methods, then that would allow me to collectAsState (with the premade extension) but no dice there. so far the conversion from Zach K has been great!