Read updates →
01Blog1 min read
← All posts

MVVM Architecture with Jetpack Compose

25 July 2023

MOriginally published on Medium ↗

Here’s a high-level overview of how you can use MVVM with Jetpack Compose in your Android app.

Model — the Model represents the data and business logic of your application. It could be your data classes, repositories or data sources.

View — in Jetpack Compose, the View is represented by composable functions that define how your UI looks. These functions take some input data and render the UI based on that data. Composable functions are annotated with @Composable and can be nested to create complex UI structures.

ViewModel — the ViewModel acts as an intermediary between the Model and the View. It holds the UI-related data needed by the View and exposes methods for the View to interact with the Model. In Jetpack Compose, you can use the ViewModel class from the androidx.lifecycle.viewmodel.compose package to create your ViewModel.

How you can implement it in your project

Let’s go through it together.

1. Create the ViewModel class

class CitiesViewModel : ViewModel() {
    private val repository = CitiesRepository()

    private val _mCities = MutableLiveData<List<Cities>>()
    val cities: LiveData<List<Cities>> = _mCities

    fun fetchCities() {
        viewModelScope.launch {
            try {
                val cities = repository.getCities()
                _mCities.value = cities
            } catch (e: Exception) {
                // Error handling
            }
        }
    }
}

2. Create the composable UI

@Composable
fun CitiesScreen(viewModel: CitiesViewModel) {
    val cities by viewModel.cities.observeAsState(emptyList())

    LaunchedEffect(Unit) {
        viewModel.fetchCities()
    }

    Column {
        if (cities.isEmpty()) {
            Text(text = "Loading...")
        } else {
            // Display the list of cities
            LazyColumn {
                items(cities) { city ->
                    Text(text = city.name)
                    Text(text = city.location)
                    Text(text = city.weather)
                }
            }
        }
    }
}

3. How the Activity will look

class MainActivity : AppCompatActivity() {
    private val viewModel: CitiesViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CitiesScreen(viewModel)
        }
    }
}

This post first appeared on Medium. Read it there and leave a clap ↗