https://kotlinlang.org logo
#compose
Title
# compose
n

Neal Sanche

02/09/2020, 7:24 PM
So, effects and the unaryPlus have been removed. How would the following code be rewritten to follow the latest fashion in Compose? I think it was originally written in an article by @Luca Nicoletti and doesn't compile anymore on Dev04:
Copy code
// general purpose observe effect. this will likely be provided by LiveData. effect API for
// compose will also simplify soon.
fun <T> observe(data: LiveData<T>) = effectOf<T?> {
    val result = +state<T?> { data.value }
    val observer = +memo { Observer<T> { result.value = it } }

    +onCommit(data) {
        data.observeForever(observer)
        onDispose { data.removeObserver(observer) }
    }

    result.value
}
Ref: https://medium.com/swlh/android-mvi-with-jetpack-compose-b0890f5156ac
a

Adam Powell

02/09/2020, 7:28 PM
Change
= effectOf<T?>
to,
: T?
in the signature (normal return value) and add
@Composable
as a function annotation, then remove the `+`s from the effect calls in the function body and add an explicit
return
keyword at the end. Change
memo
to
remember
as it was renamed.
👍🏻 2
a

Adam Powell

02/09/2020, 7:29 PM
yep, that. ☝️
n

Neal Sanche

02/09/2020, 7:30 PM
Nice I was so close... just had the return statement wrong. Will try that out, thanks guys.
👍 2
a

Adam Powell

02/09/2020, 7:33 PM
the syntax change also removes the weirdness around operator precedence that made these not work so well as extension functions or properties; you could just as easily declare this as,
Copy code
@Composable
val <T> LiveData<T>.latestValue: T? get() { ... }
if you'd prefer.
n

Neal Sanche

02/09/2020, 7:56 PM
I like that too. And, I nearly immediately run into an Exception during code generation.
Copy code
e: java.lang.IllegalStateException: Backend Internal error: Exception during code generation
Element is unknownThe root cause java.util.NoSuchElementException was thrown at: androidx.compose.plugins.kotlin.compiler.lower.ComposableCallTransformer.irComposableExpr(ComposableCallTransformer.kt:1362)

Caused by: java.util.NoSuchElementException: Collection contains no element matching the predicate.
I guess I'll go on a hunt for what might be causing that.
ViewModel uses a coroutine flow. That seems to be the root cause for me. Got way more information once I added
Copy code
composeOptions {
        kotlinCompilerVersion "1.3.61-dev-withExperimentalGoogleExtensions-20200129"
        kotlinCompilerExtensionVersion "0.1.0-dev04"
    }
Into my build.gradle.
I was able to get things working without any coroutines. Can't wait for full coroutine support in the compiler extensions.