Book Image

Simplifying Android Development with Coroutines and Flows

By : Jomar Tigcal
Book Image

Simplifying Android Development with Coroutines and Flows

By: Jomar Tigcal

Overview of this book

Coroutines and flows are the new recommended way for developers to carry out asynchronous programming in Android using simple, modern, and testable code. This book will teach you how coroutines and flows work and how to use them in building Android applications, along with helping you to develop modern Android applications with asynchronous programming using real data. The book begins by showing you how to create and handle Kotlin coroutines on Android. You’ll explore asynchronous programming in Kotlin, and understand how to test Kotlin coroutines. Next, you'll learn about Kotlin flows on Android, and have a closer look at using Kotlin flows by getting to grips with handling flow cancellations and exceptions and testing the flows. By the end of this book, you'll have the skills you need to build high-quality and maintainable Android applications using coroutines and flows.
Table of Contents (11 chapters)
1
Part 1 – Kotlin Coroutines on Android
6
Part 2 – Kotlin Flows on Android

Testing Kotlin Flows

In this section, we will focus on testing Kotlin Flows. We can create unit and integration tests for classes such as ViewModel that use Flow in their code.

To test code that collects a Flow, you can use a mock object that can return values which you can do assertion checks. For example, if your ViewModel listens to the Flow from a repository, you can create a custom Repository class that emits a Flow with a predefined set of values for easier testing.

For example, say you have a MovieViewModel class such as the following that has a fetchMovies function that collects a Flow:

class MovieViewModel(private val movieRepository:
  MovieRepository) {
    ...
    suspend fun fetchMovies() {
        movieRepository.fetchMovies().collect {
            _movies.value = it
     ...