Feedback on JetNews sample app: Many in-app compos...
# compose
m
Feedback on JetNews sample app: Many in-app composables use direct read access to global variables such as
posts
. This may work fine for simple app, but for complex app, the in-app widgets should be reusable and independent on some global state. Rather the data on which widget works should be passed as parameters. Even codelabs mention this: https://codelabs.developers.google.com/codelabs/jetpack-compose-basics/#4 I suggest that you keep actual
posts: List<Post>
as property of
MainActivity
(or its persisten state if needed), and pass this to widgets in parameters. Accessing global variables in widgets is antipattern by my opinion. I tried and it's easy achievable.
Copy code
class MainActivity : AppCompatActivity() {
    private val posts: List<Post> = listOf(
        ...
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
		// load or transform posts
        val posts = getPostsWithImagesLoaded(posts, resources)
        setContent {
            JetnewsApp(posts)
        }
    }
}
Same for
topics
and other globals.
p
I agree on the anti-pattern statement. A widget or component (call it whatever you want) should not go outside of its boundaries to get anything it needs. All its
needs
should be provided. Either by its parent or any other mechanism.
b
(I know in java) if the method was made static, it would not be able to access global state. Is there a kotlin equivalent, of a
static private
method? or am I talking heresy 😆
p
static
in java basically defines a method that is not associated with a class context or class state. It is basically a global method. Now if you declare a Global static state then the static method will have visibility to it. In kotlin you can achieve the same by declaring the function global in a file. I think that's what Composable do. Now if you declare the state Global it will have visibility to it too.
☝️ 1