All Projects → LukasLechnerDev → Kotlin Coroutine Use Cases On Android

LukasLechnerDev / Kotlin Coroutine Use Cases On Android

Licence: apache-2.0
🎓 Learning Kotlin Coroutines for Android by example. 🚀 Sample implementations for real-world Android use cases. 🛠 Unit tests included!

Programming Languages

kotlin
9241 projects

Projects that are alternatives of or similar to Kotlin Coroutine Use Cases On Android

Kotlincoroutinestests
Kotlin Coroutines Tests
Stars: ✭ 14 (-99.19%)
Mutual labels:  kotlin-coroutines
Paperplane
📚 PaperPlane - An Android reading app, including articles from Zhihu Daily, Guokr Handpick and Douban Moment.
Stars: ✭ 1,147 (-33.39%)
Mutual labels:  kotlin-coroutines
Gligar
📸Image Picker for Android, Pick an image from Gallery or Capture a new image with Camera.
Stars: ✭ 96 (-94.43%)
Mutual labels:  kotlin-coroutines
Eyepetizer
🔥基于 Kotlin 语言仿写「开眼 Eyepetizer」的一个短视频 Android 客户端项目,采用 Jetpack + 协程实现的 MVVM 架构。
Stars: ✭ 988 (-42.62%)
Mutual labels:  kotlin-coroutines
Easychatandroidclient
EasyChat是一个开源的社交类的App。主要包含消息、好友、群组等相关的IM核心功能。部分界面参照了QQ、微信等相关社交APP。EasyChat APP整体采用MVVM模式,基于JetPack(Lifecycle,LiveData,ViewModel,Room)构建
Stars: ✭ 64 (-96.28%)
Mutual labels:  kotlin-coroutines
Kuroba Experimental
Free and open source image board browser
Stars: ✭ 76 (-95.59%)
Mutual labels:  kotlin-coroutines
Peopleinspace
Minimal Kotlin Multiplatform project using Jetpack Compose and SwiftUI
Stars: ✭ 887 (-48.49%)
Mutual labels:  kotlin-coroutines
Kotlincoroutinesexamples
Kotlin Coroutines Examples
Stars: ✭ 109 (-93.67%)
Mutual labels:  kotlin-coroutines
Comicreaderapp mvi coroutine rxkotlin jetpack
⚡️Comic reader app 📘. Learning MVVM / MVI with 🌀 RxKotlin, Retrofit, Kotlin Coroutine, Work Manager, Room, Firebase, AndroidX Startup, Clean Architecture ... ❄️
Stars: ✭ 67 (-96.11%)
Mutual labels:  kotlin-coroutines
Covid 19 Tracker
Android app to track COVID-19 cases in India and globally.
Stars: ✭ 96 (-94.43%)
Mutual labels:  kotlin-coroutines
Posts Mvvm Daggerhilt Dynamic Feature Rxjava3 Flow Sample
Posts Api sample with Kotlin RxJava3/Coroutines Flow, Clean Architecture, Offline first/last with Room + Retrofit2, Dagger Hilt, Dynamic Feature Modules, Static Code Analysis, Gradle DSL, MockK+ MockWebServer with Test Driven Development including Api and Database tests
Stars: ✭ 41 (-97.62%)
Mutual labels:  kotlin-coroutines
Multiplatform
Kotlin Multiplatform(Android/iOS) project.
Stars: ✭ 50 (-97.1%)
Mutual labels:  kotlin-coroutines
Asynkio
Write your asynchronous Network / IO call painlessly in Kotlin !!
Stars: ✭ 82 (-95.24%)
Mutual labels:  kotlin-coroutines
Ktx
LibKTX: Kotlin extensions for LibGDX games and applications
Stars: ✭ 913 (-46.98%)
Mutual labels:  kotlin-coroutines
Android Coroutines
Additional coroutine support for Android
Stars: ✭ 105 (-93.9%)
Mutual labels:  kotlin-coroutines
Myweatherkotlinflow
Android app that shows weather at your current location or any custom location you specify. Uses Kotlin Flow for data streaming and coroutines for asynchronous work. Also leverages Room, navigation component, Viewmodel and Livedata Jetpack components with MVVM presentation layer architecture. Dagger 2 with Dagger android for dependency injection
Stars: ✭ 23 (-98.66%)
Mutual labels:  kotlin-coroutines
Kotlin Coroutines Android
Useful extensions for coroutines. AutoDispose + MainScope
Stars: ✭ 77 (-95.53%)
Mutual labels:  kotlin-coroutines
Cameraxdemo
A sample camera app with CameraX API from Android Jetpack
Stars: ✭ 112 (-93.5%)
Mutual labels:  kotlin-coroutines
Coroutinerecipes
Playground for Kotlin Coroutines. Basics, Channels, Flows, useful examples & comparison to RxJava.
Stars: ✭ 104 (-93.96%)
Mutual labels:  kotlin-coroutines
Kotlintutorial
Learn Kotlin programming from scratch
Stars: ✭ 88 (-94.89%)
Mutual labels:  kotlin-coroutines

CoroutineUsecasesOnAndroid

Kotlin Coroutines - Use Cases on Android

🎓 Learning Kotlin Coroutines for Android by example.

🚀 Sample implementations for real-world Android use cases.

🛠 Unit tests included!

This repository is intended to be a "Playground Project". You can quickly look up and play around with the different Coroutine Android implementations. In the playground package you can play around with Coroutines examples that run directly on the JVM.

🔧 Project Setup

Every use case is using its own Activity and JetPack ViewModel. The ViewModels contain all the interesting Coroutine related code. Activities listen to LiveData events of the ViewModel and render received UiStates.

This project is using retrofit/okhttp together with a MockNetworkInterceptor. This lets you define how the API should behave. Everything can be configured: http status codes, response data and delays. Every use case defines a certain behaviour of the Mock API. The API has 2 endpoints. One returns the names of the most recent Android versions and the other one returns the features of a certain Android version.

Unit Tests exist for most use cases.

🍿️ Related Videos

  • Kotlin Coroutines Fundamentals Playlist [link]
  • Kotlin Coroutines Exception Handling explained [link]

✍️ Related blog posts

  • 7 Common Mistakes you might be making when using Kotlin Coroutines [link]
  • Why exception handling with Kotlin Coroutines is so hard and how to successfully master it! [link]
  • Kotlin Coroutines exception handling cheat sheet [link]
  • Understanding Kotlin Coroutines with this mental model [link]
  • Do I need to call suspend functions of Retrofit and Room on a background thread? [link]
  • Comparing Kotlin Coroutines with Callbacks and RxJava [link]
  • How to run an expensive calculation with Kotlin Coroutines on the Android Main Thread without freezing the UI [link]

Sign up to my newsletter to never miss a new blog post. I will publish new blog posts about Coroutines on a regular basis.

🎓 Online Course

This project is the foundation of a comprehensive Online Course about Mastering Kotlin Coroutines for Android Development

CourseCoroutinesOnAndroid

📢 Sharing is Caring

If you like this project, please tell other developers about it! ❤️

Share on Twitter

If you like, you can follow me on Twitter @LukasLechnerDev.

⭐️ Use Cases

  1. Perform single network request
  2. Perform two sequential network requests
  3. Perform several network requests concurrently
  4. Perform variable amount of network requests
  5. Perform a network request with timeout
  6. Retrying network requests
  7. Network requests with timeout and retry
  8. Room and Coroutines
  9. Debugging Coroutines
  10. Offload expensive calculation to background thread
  11. Cooperative Cancellation
  12. Offload expensive calculation to several Coroutines
  13. Exception Handling
  14. Continue Coroutine execution even when the user leaves the screen
  15. Using WorkManager with Coroutines
  16. Performance analysis of dispatchers, number of coroutines and yielding
  17. Perform expensive calculation on Main Thread without freezing the UI

📄 Description

1. Perform single network request

This use case performs a single network request to get the latest Android Versions and displays them on the screen.

[code]

2. Perform two sequential network requests

This use case performs two network requests sequentially. First it retrieves recent Android Versions and then it requests the features of the latest version.

There are also 2 alternative implementations included. One is using old-school callbacks. The other one uses RxJava. You can compare each implementation. If you compare all three implementations, it is really interesting to see, in my opinion, how simple the Coroutine-based version actually is.

[code]

3. Perform several network requests concurrently

Performs three network requests concurrently. It loads the feature information of the 3 most recent Android Versions. Additionally, an implementation that performs the requests sequentially is included. The UI shows how much time each implementation takes to load the data so you can see that the network requests in the concurrent version are actually performed in parallel. The included unit test is also interesting, as it shows how you can use virtual time to verify that the concurrent version really gets performed in parallel.

[code]

4. Perform variable amount of network requests

Demonstrates the simple usage of map() to perform a dynamic amount of network requests. At first, this use case performs a network request to load all Android versions. Then it performs a network request for each Android version to load its features. It contains an implementation that performs the network requests sequentially and another one that performs them concurrently.

[code]

5. Perform network request with timeout

This use case uses the suspending function withTimeout() from the coroutines-core library. It throws a TimeoutCancellationException if the timeout was exceeded. You can set the duration of the request in the UI and check the behaviour when the response time is bigger than the timeout.

General networking timeouts can also be configured in the okhttp client.

[code]

6. Retrying network requests

Demonstrates the usage of higher order functions together with coroutines. The higher order function retry() retries a certain suspending operation for a given amount of times. It uses an exponential backoff for retries, which means that the delay between retries increases exponentially. The behavior of the Mock API is defined in a way that it responses with 2 unsuccessful responses followed by a successful response.

[code]

Unit tests verify the amount of request that are performed in different scenarios. Furthermore they check if the exponential backoff is working properly by asserting the amount of elapsed virtual time.

7. Network requests with timeout and retry

Composes higher level functions retry() and withTimeout(). Demonstrates how simple and readable code written with Coroutines can be. The mock API first responds after the timeout and then returns an unsuccessful response. The third attempt is then successful.

Take a look at the included callback-based implementation to see how tricky this use case is to implement without Coroutines.

I also implemented the use case with RxJava.

[code]

8. Room and Coroutines

This example stores the response data of each network request in a Room database. This is essential for any "offline-first" app. If the View requests data, the ViewModel first checks if there is data available in the database. If so, this data is returned before performing a network request to get fresh data.

[code]

9. Debugging Coroutines

This is not really a use case, but I wanted to show how you can add additional debug information about the Coroutine that is currently running to your logs. It will add the Coroutine name next to the thread name when calling Thread.currentThread.name() This is done by enabling Coroutine Debug mode by setting the property kotlinx.coroutines.debug to true.

[code]

10. Offload expensive calculation to background thread

This use case calculates the factorial of a number. The calculation is performed on a background thread using the default Dispatcher.

Attention: This use case does not support cancellation! UseCase#11 fixes this!

[code]

In the respective unit test, we have to pass the testDispatcher to the ViewModel, so that the calculation is not performed on a background thread but on the main thread.

11. Cooperative cancellation

UseCase#10 has a problem. It is not able to prematurely cancel the calculation because it is not cooperative regarding cancellation. This leads to wasted device resources and memory leaks, as the calculation is not stopped and ViewModel is retained longer than necessary. This use case now fixes this issue. The UI now also has a "Cancel Calculation" Button. Note: Only the calculation can be cancelled prematurely but not the toString() conversion.

There are several ways to make your coroutines cooperative regarding cancellation: You can use either use isActive(), ensureActive() or yield(). More information about cancellation can be found here

[code]

12. Offload expensive calculation to several Coroutines

The factorial calculation here is not performed by a single coroutine, but by an amount of coroutines that can be defined in the UI. Each coroutine calculates the factorial of a sub-range.

[code viewmodel] [code factorial calculator]

13. Exception Handling

This use case demonstrates different ways of handling exceptions using try/catch and CoroutineExceptionHandler. It also demonstrates when you should to use supervisorScope{}: In situations when you don't want a failing coroutine to cancel its sibling coroutines. In one implementation of this use case, the results of the successful responses are shown even tough one response wasn't successful.

[code]

14. Continue Coroutine execution when the user leaves the screen

Usually, when the user leaves the screen, the ViewModel gets cleared and all the coroutines launched in viewModelScope get cancelled. Sometimes, however, we want a certain coroutine operation to be continued when the user leaves the screen. In this use case, the network request keeps running and the results still get inserted into the database cache when the user leaves the screen. This makes sense in real world application as we don't want to cancel an already started background "cache sync".

You can test this behavior in the UI by clearing the database, then loading the Android version and instantly close the screen. You will see in LogCat that the response still gets executed and the result still gets stored. The respective unit test AndroidVersionRepositoryTest also verifies this behavior. Check out this blogpost for details of the implementation.

[code viewmodel] [code repository]

15. Using WorkManager with Coroutines

Demonstrates how you can use WorkManager together with Coroutines. When creating a subclass of CoroutineWorker instead of Worker, the doWork() function is now a suspend function which means that we can now call other suspend functions. In this example, we are sending an analytics request when the user enters the screen, which is a nice use case for using WorkManager.

[code viewmodel] [code worker]

16. Performance analysis of dispatchers, number of coroutines and yielding

This is an extension of use case #12 (Offload expensive calculation to several coroutines). Here it is possible to additionally define the dispatcher type you want the calculation to be performed on. Additionally, you can enable or disable the call to yield() during the calculation. A list of calculations is displayed on the bottom in order to be able to compare them in a convenient way.

17. Perform expensive calculation on Main Thread without freezing the UI

This example shows how you can perform an expensive calculation on the main thread in a non-blocking fashion. It uses yield() for every step in the calculation so that other work, like drawing the UI, can be performed on the main thread. It is more a "showcase" rather than a use case for a real application, because of performance reasons you should always perform expensive calculations on a background thread (See UseCase#10). See [this blog post] for more information!

You can play around and check the performance of different configurations!

👷‍♀️ Contributing 👷‍♂️

I am currently learning Coroutines myself. So if you have any ideas for or improvements or other use cases, feel free to create a pull request or an issue.

Author

LukasLechner

Lukas Lechner

Twitter

License

Licensed under the Apache License, Version 2.0 (the "License"). You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

You agree that all contributions to this repository, in the form of fixes, pull-requests, new examples etc. follow the above-mentioned license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].