content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.scarlet.coroutines.testing.version2
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.scarlet.coroutines.android.livedata.ApiService
import com.scarlet.model.Article
import com.scarlet.util.Resource
import kotlinx.coroutines.*
class ArticleViewModel(
private val apiService: ApiService,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : ViewModel() {
private val _articles = MutableLiveData<Resource<List<Article>>>()
val articles: LiveData<Resource<List<Article>>>
get() = _articles
fun onButtonClicked() {
viewModelScope.launch(dispatcher) {
loadData()
}
}
private suspend fun loadData() {
val articles = networkRequest()
update(articles)
}
private suspend fun networkRequest(): Resource<List<Article>> {
return apiService.getArticles()
}
private fun update(articles: Resource<List<Article>>) {
_articles.value = articles
}
}
| KotlinCoroutines-demo/app/src/test/java/com/scarlet/coroutines/testing/version2/ArticleViewModel.kt | 994318924 |
package com.scarlet.coroutines.testing.version2
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.google.common.truth.Truth.assertThat
import com.scarlet.coroutines.android.livedata.ApiService
import com.scarlet.model.Article
import com.scarlet.util.Resource
import com.scarlet.util.getValueForTest
import com.scarlet.util.log
import com.scarlet.util.testDispatcher
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ExperimentalCoroutinesApi
class SetMainTest {
@get:Rule
val rule = InstantTaskExecutorRule()
private val testArticles = Resource.Success(Article.articleSamples)
@MockK
private lateinit var mockApiService: ApiService
// SUT
private lateinit var viewModel: ArticleViewModel
// TODO: Create a test dispatcher
@Before
fun init() {
MockKAnnotations.init(this)
coEvery { mockApiService.getArticles() } coAnswers {
log("coAnswers")
delay(3_000)
testArticles
}
}
@Test
fun `test fun creating new coroutines`() = runTest {
// Given
viewModel = ArticleViewModel(mockApiService, testDispatcher)
// When
viewModel.onButtonClicked()
advanceUntilIdle()
// Then
coVerify { mockApiService.getArticles() }
val articles = viewModel.articles.getValueForTest()
assertThat(articles).isEqualTo(testArticles)
}
}
| KotlinCoroutines-demo/app/src/test/java/com/scarlet/coroutines/testing/version2/SetMainTest.kt | 2109805994 |
package com.scarlet.coroutines.migration
import com.google.common.truth.Truth.assertThat
import com.scarlet.model.Recipe
import com.scarlet.model.Recipe.Companion.mRecipes
import com.scarlet.util.Resource
import io.mockk.*
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.*
import kotlinx.coroutines.test.runTest
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.concurrent.Executors.*
import java.util.concurrent.TimeUnit
class CvtToSuspendingFunctionTest {
@MockK
lateinit var mockApi: RecipeApi
@MockK(relaxed = true)
lateinit var mockCall: Call<List<Recipe>>
@MockK
lateinit var mockResponse: Response<List<Recipe>>
@Before
fun init() {
MockKAnnotations.init(this)
every { mockApi.search(any(), any()) } returns mockCall
}
@Test
fun `Callback - should return valid recipes`() {
// Arrange (Given)
val slot = slot<Callback<List<Recipe>>>()
every { mockResponse.isSuccessful } returns true
every { mockResponse.body() } returns mRecipes
every { mockCall.enqueue(capture(slot)) } answers {
slot.captured.onResponse(mockCall, mockResponse)
}
val target = UsingCallback_Demo2
// Act (When)
target.searchRecipes("eggs", mockApi, object : RecipeCallback<List<Recipe>> {
override fun onSuccess(response: Resource<List<Recipe>>) {
// Assert (Then)
assertThat(response).isEqualTo(Resource.Success(mRecipes))
}
override fun onError(response: Resource<List<Recipe>>) {
fail("Should not be called")
}
})
}
@ExperimentalCoroutinesApi
@Test
fun `Suspending Function - should return valid recipes`() = runTest {
// Arrange (Given)
val slot = slot<Callback<List<Recipe>>>()
every { mockResponse.isSuccessful } returns true
every { mockResponse.body() } returns mRecipes
every { mockCall.enqueue(capture(slot)) } answers {
slot.captured.onResponse(mockCall, mockResponse)
}
val target = CvtToSuspendingFunction_Demo2
// Act (When)
val response = target.searchRecipes("eggs", mockApi, TODO())
// Assert (Then)
assertThat(response).isEqualTo(Resource.Success(mRecipes))
}
@Test
fun `Suspending Function - should cancel searchRecipes`() = runBlocking {
// Arrange (Given)
val slot = slot<Callback<List<Recipe>>>()
every { mockResponse.isSuccessful } returns true
every { mockResponse.body() } returns mRecipes
every {
mockCall.enqueue(capture(slot))
} answers {
newSingleThreadScheduledExecutor().schedule({
slot.captured.onResponse(mockCall, mockResponse)
}, 1, TimeUnit.SECONDS)
}
val target = CvtToSuspendingFunction_Demo2
// Act (When)
val job = launch {
target.searchRecipes("eggs", mockApi, TODO())
}
delay(500)
job.cancelAndJoin()
// Assert (Then)
verify { mockCall.cancel() }
}
} | KotlinCoroutines-demo/app/src/test/java/com/scarlet/coroutines/migration/CvtToSuspendingFunctionTest.kt | 4252072775 |
package com.scarlet.coffeeshop.util
fun log(v: Any) = println("[${Thread.currentThread().name}] $v")
fun Float.format(digits: Int): String = java.lang.String.format("%.${digits}f", this) | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coffeeshop/util/Util.kt | 2468805399 |
package com.scarlet.coffeeshop
import com.scarlet.coffeeshop.model.*
import com.scarlet.coffeeshop.util.log
import java.lang.Thread.sleep
import kotlin.system.measureTimeMillis
fun main() {
val orders = listOf(
Menu.Cappuccino(CoffeeBean.Regular, Milk.Whole),
Menu.Cappuccino(CoffeeBean.Premium, Milk.Breve),
Menu.Cappuccino(CoffeeBean.Regular, Milk.NonFat),
Menu.Cappuccino(CoffeeBean.Decaf, Milk.Whole),
Menu.Cappuccino(CoffeeBean.Regular, Milk.NonFat),
Menu.Cappuccino(CoffeeBean.Decaf, Milk.NonFat)
).onEach { log(it) }
val time = measureTimeMillis {
orders.forEach {
log("Processing order: $it")
val groundBeans = grindCoffeeBeans(it.beans)
val espresso = pullEspressoShot(groundBeans)
val steamedMilk = steamMilk(it.milk)
val cappuccino = makeCappuccino(it, espresso, steamedMilk)
log("serve: $cappuccino")
}
}
log("time: $time ms")
}
private fun grindCoffeeBeans(beans: CoffeeBean): CoffeeBean.GroundBeans {
log("grinding coffee beans")
sleep(1000)
return CoffeeBean.GroundBeans(beans)
}
private fun pullEspressoShot(groundBeans: CoffeeBean.GroundBeans): Espresso {
log("pulling espresso shot")
sleep(600)
return Espresso(groundBeans)
}
private fun steamMilk(milk: Milk): Milk.SteamedMilk {
log("steaming milk")
sleep(300)
return Milk.SteamedMilk(milk)
}
private fun makeCappuccino(
order: Menu.Cappuccino,
espresso: Espresso,
steamedMilk: Milk.SteamedMilk
): Beverage.Cappuccino {
log("making cappuccino")
sleep(100)
return Beverage.Cappuccino(order, espresso, steamedMilk)
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coffeeshop/CoffeeShop1.kt | 952482405 |
package com.scarlet.coffeeshop.model
import com.scarlet.coffeeshop.util.format
sealed class Menu {
abstract fun price(): Float
abstract fun beans(): CoffeeBean
abstract fun milk(): Milk
data class Cappuccino(val beans: CoffeeBean, val milk: Milk): Menu() {
override fun price() = 3.50f + beans.price() + milk.price()
override fun beans() = beans
override fun milk() = milk
override fun toString() = "cappuccino: beans=$beans milk=$milk price=$${price().format(2)}"
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coffeeshop/model/Menu.kt | 2573342412 |
package com.scarlet.coffeeshop.model
sealed class CoffeeBean {
abstract fun price(): Float
object Premium: CoffeeBean() {
override fun price() = 1.00f
override fun toString() = "premium"
}
object Regular: CoffeeBean() {
override fun price() = 0.00f
override fun toString() = "regular"
}
object Decaf: CoffeeBean() {
override fun price() = 0.50f
override fun toString() = "decaf"
}
data class GroundBeans(val coffeeBean: CoffeeBean): CoffeeBean() {
override fun price() = 0.00f
override fun toString() = "ground $coffeeBean"
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coffeeshop/model/CoffeeBean.kt | 1852217002 |
package com.scarlet.coffeeshop.model
sealed class Beverage {
data class Cappuccino(val order: Menu.Cappuccino, val espressoShot: Espresso, val steamedMilk: Milk.SteamedMilk): Beverage()
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coffeeshop/model/Beverage.kt | 271238686 |
package com.scarlet.coffeeshop.model
data class Espresso(val beans: CoffeeBean.GroundBeans) | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coffeeshop/model/Espresso.kt | 3204097106 |
package com.scarlet.coffeeshop.model
sealed class Milk {
abstract fun price(): Float
object Whole: Milk() {
override fun price() = 0.00f
override fun toString() = "whole milk"
}
object NonFat: Milk() {
override fun price() = 0.00f
override fun toString() = "non-fat milk"
}
object Breve: Milk() {
override fun price() = 1.00f
override fun toString() = "breve"
}
data class SteamedMilk(val milk: Milk): Milk() {
override fun price() = 0.00f
override fun toString() = "steamed milk"
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coffeeshop/model/Milk.kt | 2543637911 |
package com.scarlet.coffeeshop
class EspressoMachine | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coffeeshop/EspressoMachine.kt | 3667009342 |
package com.scarlet
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/MainActivity.kt | 606019740 |
package com.scarlet.util
import kotlinx.coroutines.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.coroutines.ContinuationInterceptor
val log: Logger = LoggerFactory.getLogger("Coroutines")
fun log(msg: Any?) {
log.info(msg.toString())
}
fun delim(char: String = "-", length: Int = 50) {
log(char.repeat(length))
}
fun spaces(level: Int) = "\t".repeat(level)
fun CoroutineScope.coroutineInfo(indent: Int) {
delim()
log("\t".repeat(indent) + "thread = ${Thread.currentThread().name}")
log("\t".repeat(indent) + "job = ${coroutineContext[Job]}")
log("\t".repeat(indent) + "dispatcher = ${coroutineContext[ContinuationInterceptor]}")
log("\t".repeat(indent) + "name = ${coroutineContext[CoroutineName]}")
log("\t".repeat(indent) + "handler = ${coroutineContext[CoroutineExceptionHandler]}")
delim()
}
@ExperimentalStdlibApi
fun scopeInfo(scope: CoroutineScope, indent: Int) {
delim()
log("\t".repeat(indent) + "Scope's job = ${scope.coroutineContext[Job]}")
log("\t".repeat(indent) + "Scope's dispatcher = ${scope.coroutineContext[CoroutineDispatcher]}")
log("\t".repeat(indent) + "Scope's name = ${scope.coroutineContext[CoroutineName]}")
log("\t".repeat(indent) + "Scope's handler = ${scope.coroutineContext[CoroutineExceptionHandler]}")
delim()
}
fun Job.completeStatus(name: String = "Job", level: Int = 0) = apply {
log("${spaces(level)}$name: isCancelled = $isCancelled")
}
fun CoroutineScope.completeStatus(name: String = "scope", level: Int = 0) = apply {
log("${spaces(level)}$name: isCancelled = ${coroutineContext.job.isCancelled}")
}
fun CoroutineScope.onCompletion(name: String): CoroutineScope = apply {
coroutineContext.job.invokeOnCompletion {
log("$name: isCancelled = ${coroutineContext.job.isCancelled}, exception = ${it?.javaClass?.name}")
}
}
fun Job.onCompletion(name: String, level: Int = 0): Job = apply {
invokeOnCompletion {
log("${spaces(level)}$name: isCancelled = $isCancelled, exception = ${it?.javaClass?.name}")
}
}
fun <T> Deferred<T>.onCompletion(name: String, level: Int = 0): Deferred<T> = apply {
invokeOnCompletion {
log("${spaces(level)}$name: isCancelled = $isCancelled, exception = ${it?.javaClass?.name}")
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/util/Utils.kt | 1120687815 |
package com.scarlet.util
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
interface DispatcherProvider {
val main: CoroutineDispatcher
val mainImmediate: CoroutineDispatcher
val default: CoroutineDispatcher
val io: CoroutineDispatcher
val unconfined: CoroutineDispatcher
}
class DefaultDispatcherProvider(
override val main: CoroutineDispatcher = Dispatchers.Main,
override val mainImmediate: CoroutineDispatcher = Dispatchers.Main.immediate,
override val default: CoroutineDispatcher = Dispatchers.Default,
override val io: CoroutineDispatcher = Dispatchers.IO,
override val unconfined: CoroutineDispatcher = Dispatchers.Unconfined,
) : DispatcherProvider | KotlinCoroutines-demo/app/src/main/java/com/scarlet/util/DispatcherProvider.kt | 2904220906 |
package com.scarlet.util
/**
* A generic class that holds a value with its loading status.
*/
sealed class Resource<out R> {
data class Success<out T>(val data: T?) : Resource<T>()
data class Error(val message: String?) : Resource<Nothing>()
object Loading : Resource<Nothing>()
override fun toString(): String {
return when (this) {
is Success -> "Success[data=$data]"
is Error -> "Error[message=$message]"
is Loading -> "Loading"
}
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/util/Resource.kt | 1878251021 |
package com.scarlet.model
data class Article(val id: String, val author: String, val title: String) {
companion object {
val articleSamples = listOf(
Article("A001", "Robert Martin", "Clean Code"),
Article("A002", "Jungsun Kim", "Android Testing in Kotlin"),
Article("A003", "Kent Beck", "Extreme Programming"),
Article("A004", "Robert Martin", "Agile Patterns"),
Article("A005", "Sean McQuillan", "Android Testing"),
Article("A006", "Roman Elizarov", "Kotlin Coroutines")
)
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/model/Article.kt | 2525659547 |
package com.scarlet.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Recipe(
@PrimaryKey
@ColumnInfo(name = "recipe_id") val recipeId: String,
@ColumnInfo(name = "title") val title: String?) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Recipe
if (recipeId != other.recipeId) return false
if (title != other.title) return false
return true
}
override fun hashCode(): Int {
var result = recipeId.hashCode()
result = 31 * result + (title?.hashCode() ?: 0)
return result
}
companion object {
val recipe1 = Recipe("1af01c", "Cakespy: Cadbury Creme Deviled Eggs")
val recipe2 = Recipe("1cea66", "Poached Eggs in Tomato Sauce with Chickpeas and Feta")
var mRecipes = listOf(recipe1, recipe2)
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/model/Recipe.kt | 828627281 |
package com.scarlet.model
data class User(val id: String, val name: String, var age: Int) | KotlinCoroutines-demo/app/src/main/java/com/scarlet/model/User.kt | 1532717919 |
package com.scarlet.coroutines.cancellation
import com.scarlet.util.log
import kotlinx.coroutines.*
object Uncooperative_Cancellation {
private suspend fun printTwice() = withContext(Dispatchers.Default) {
val startTime = System.currentTimeMillis()
var nextPrintTime = startTime
while (true) {
if (System.currentTimeMillis() >= nextPrintTime) {
log("I'm working..")
nextPrintTime += 500
}
}
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val job = launch {
printTwice()
}
delay(1_500)
log("Cancelling job ...")
job.cancelAndJoin()
}
}
/**
* CoroutineScope.{isActive, ensureActive()} and delay()
*
* Think about how to handle cleanup?
*/
object Cooperative_Cancellation {
// How to make sure this suspending function be cooperative?
private suspend fun printTwice() = withContext(Dispatchers.Default) {
val startTime = System.currentTimeMillis()
var nextPrintTime = startTime
while (true) {
if (System.currentTimeMillis() >= nextPrintTime) {
println("I'm working..")
nextPrintTime += 500
}
}
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val job = launch {
printTwice()
}
delay(1500)
log("Cancelling job ...")
job.cancelAndJoin()
}
}
object Cleanup_When_Cancelled {
private suspend fun printTwice() = withContext(Dispatchers.Default) {
val startTime = System.currentTimeMillis()
var nextPrintTime = startTime
while (isActive) {
if (System.currentTimeMillis() >= nextPrintTime) {
log("job: I'm working..")
nextPrintTime += 500
}
}
// TODO: cleanup
log("job: I'm cancelled")
cleanUp()
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val job = launch {
printTwice()
}
delay(1_500)
log("Try to cancel the job ...")
job.cancelAndJoin()
}
private suspend fun cleanUp() {
delay(100)
log("Cleanup ...")
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/cancellation/C03_CooperationForCancellation.kt | 2013785698 |
package com.scarlet.coroutines.cancellation
import com.scarlet.util.log
import com.scarlet.util.onCompletion
import kotlinx.coroutines.*
import java.lang.Exception
/**
* If **Job** is already in a _Cancelling_ state, then suspension or starting
* another coroutine is not possible at all.
*
* If we try to start another coroutine, it will just be _ignored_.
*
* If we try to suspend, it will throw `CancellationException`.
*/
object Try_Launch_Or_Call_Suspending_Function_in_Canceling_State {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val job = launch {
try {
delay(200)
log("Unreachable code") // because it will be cancelled after 100ms
} finally {
log("Finally")
log("isActive = ${coroutineContext.isActive}, isCancelled = ${coroutineContext.job.isCancelled}")
// Try to launch new coroutine
launch { // will be ignored because of immediate cancellation
log("Will not be printed")
delay(50)
}.onCompletion("Jombi")//.join() // will throw cancellation exception and skip the rest
// Try to call suspending function will throw cancellation exception
try {
delay(100)
log("Will not be printed")
} catch (ex: Exception) {
log("Caught: $ex")
}
// Nevertheless, if you want to call suspending function to clean up ... how to do?
}
}
delay(100)
job.cancelAndJoin()
log("Cancel done")
}
}
object Call_Suspending_Function_in_Cancelling_State_To_Cleanup {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val job = launch {
try {
delay(200)
println("Coroutine finished")
} finally {
println("Finally")
// DO NOT USE NonCancellable with `launch` or `async`
cleanUp()
println("Cleanup done")
}
}
delay(100)
job.cancelAndJoin()
println("Cancel done")
}
private suspend fun cleanUp() {
delay(3_000)
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/cancellation/C02_NonCancellable.kt | 84671817 |
package com.scarlet.coroutines.cancellation
import com.scarlet.util.completeStatus
import com.scarlet.util.log
import com.scarlet.util.onCompletion
import kotlinx.coroutines.*
/**
* The **`Job`** interface has a method `cancel`, that allows its cancellation.
* Calling it triggers the following effects:
* - Such a coroutine ends the job _at the first suspension point_ (such as `delay()`).
* - If a job has some children, they are canceled too.
* - Once a job is canceled, it cannot be used as a parent for any new coroutines,
* it is first in _Cancelling_ and then in _Cancelled_ state.
*/
object Cancel_Parent_Scope {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
val scope = CoroutineScope(Job())
var child: Job? = null
val parent = scope.launch {
child = launch {
delay(1_000)
log("child is done")
}.onCompletion("child")
}.onCompletion("parent")
delay(100)
// precarious !@#$
scope.cancel() // What should we do to wait for all the children to be completed in cancelled state?
log("parent cancelled = ${parent.isCancelled}")
log("child cancelled = ${child?.isCancelled}")
scope.completeStatus("scope")
}
}
object Cancel_Parent_Coroutine {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
val scope = CoroutineScope(Job())
var child1: Job? = null
var child2: Job? = null
val parentJob = scope.launch {
child1 =
launch { delay(1_000) }.onCompletion("child1")
child2 =
launch { delay(1_000) }.onCompletion("child2")
}.onCompletion("parentJob")
delay(200)
parentJob.cancelAndJoin()
log("parent job cancelled = ${parentJob.isCancelled}")
log("child1 job cancelled = ${child1?.isCancelled}")
log("child2 job cancelled = ${child2?.isCancelled}")
scope.completeStatus("scope")
}
}
object Cancel_Child_Coroutine {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
val scope = CoroutineScope(Job())
var child1: Job? = null
var child2: Job? = null
val parentJob = scope.launch {
child1 =
launch { delay(1_000) }.onCompletion("child1")
child2 =
launch { delay(1_000) }.onCompletion("child2")
}.onCompletion("parentJob")
delay(200)
child1?.cancel()
parentJob.join()
log("parent job cancelled = ${parentJob.isCancelled}")
log("child1 job cancelled = ${child1?.isCancelled}")
log("child2 job cancelled = ${child2?.isCancelled}")
scope.completeStatus("scope")
}
}
/**
* Quiz
*/
object Cancel_Parent_Job_Quiz {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
val scope = CoroutineScope(Job())
val job = Job()
// Who's my parent?
val child = scope.launch(job) {
delay(1_000)
}.onCompletion("child")
delay(100)
// How to cancel the child via its parent?
// job.cancel() or scope.cancel() ?
child.join()
delay(500)
log("child cancelled = ${child.isCancelled}")
scope.completeStatus("scope")
}
}
object Cancel_Children_Only_To_Reuse_Parent_Job {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
val scope = CoroutineScope(Job())
var child1: Job? = null
var child2: Job? = null
val parentJob = scope.launch {
child1 = launch { delay(1_000) }.onCompletion("child1")
child2 = launch { delay(1_000) }.onCompletion("child2")
}.onCompletion("parentJob")
delay(200)
parentJob.cancelChildren()
parentJob.join()
log("parent job cancelled = ${parentJob.isCancelled}")
log("child1 job cancelled = ${child1?.isCancelled}")
log("child2 job cancelled = ${child2?.isCancelled}")
scope.completeStatus("scope")
}
}
object Cancel_Children_Only_To_Reuse_Scope {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
val scope = CoroutineScope(Job())
var child1: Job? = null
var child2: Job? = null
val parentJob = scope.launch {
child1 = launch { delay(1_000) }.onCompletion("child1")
child2 = launch { delay(1_000) }.onCompletion("child2")
}.onCompletion("parentJob")
delay(200)
scope.coroutineContext.job.cancelChildren()
parentJob.join()
log("parent job cancelled = ${parentJob.isCancelled}")
log("child1 job cancelled = ${child1?.isCancelled}")
log("child2 job cancelled = ${child2?.isCancelled}")
scope.completeStatus("scope")
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/cancellation/C01_Cancellation.kt | 1026390356 |
package com.scarlet.coroutines.basics
import com.scarlet.util.log
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
object Create_Coroutine_With_RunBlocking_Demo1 {
@JvmStatic
fun main(args: Array<String>) {
log("Hello")
runBlocking {
log("Coroutine created")
delay(1_000)
log("Coroutine done")
}
log("World")
}
}
object Create_Coroutine_With_RunBlocking_Demo2 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("Coroutine created")
delay(1_000)
log("Coroutine done")
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/basics/B01_RunBlocking.kt | 1474635507 |
package com.scarlet.coroutines.basics
import com.scarlet.model.User
import com.scarlet.util.log
import kotlinx.coroutines.*
private suspend fun getUser(userId: String): User {
log("\tinside getUser $userId")
delay(1_000)
return User("A001", "Sara Corner", 33)
}
object Async_Demo1 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val deferred = async {
log("\tRequest user with Id A001")
getUser("A001")
}
log("Waiting for results ...")
val user = deferred.await()
log("Returned user = $user")
log("Done")
}
}
// DON'T DO THIS
@DelicateCoroutinesApi
object Async_Demo2 {
@ExperimentalStdlibApi
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val deferred = GlobalScope.async {
log("\tRequest user with Id A001")
getUser("A001")
}
log("Waiting for results ...")
val user = deferred.await()
log("Returned user = $user")
log("Done")
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/basics/B03_Async.kt | 2952336632 |
package com.scarlet.coroutines.basics
import com.scarlet.util.log
import kotlinx.coroutines.*
import java.lang.RuntimeException
object Nested_Coroutines {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
log("Top-Level Coroutine")
launch {
log("\tLevel 1 Coroutine")
launch {
log("\t\tLevel 2 Coroutine")
launch { log("\t\t\tLevel 3 Coroutine") }
launch { log("\t\t\tLevel 3 Another Coroutine") }
}
}
}
}
/**
* Structured Concurrency Preview
*/
object Canceling_parent_coroutine_cancels_the_parent_and_its_children {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val parent = launch {
val child1 = launch {
log("\t\tchild1 started")
delay(1_000)
log("\t\tchild1 done")
}
val child2 = launch {
log("\t\tchild2 started")
delay(1_000)
log("\t\tchild2 done")
}
log("\tparent is waiting")
joinAll(child1, child2)
log("\tparent done")
}
parent.join()
// delay(500)
// parent.cancel() // parent.cancelAndJoin()
log("Done")
}
}
object Canceling_a_child_cancels_only_the_child {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
var child1: Job? = null
val parent = launch {
child1 = launch {
log("\t\tchild1 started")
delay(1_000)
log("\t\tchild1 done")
}
val child2 = launch {
log("\t\tchild2 started")
delay(1_000)
log("\t\tchild2 done")
}
log("\tparent is waiting")
joinAll(child1!!, child2)
log("\tparent done")
}
delay(500)
child1?.cancel()
parent.join()
log("Done")
}
}
object Failed_parent_causes_cancellation_of_all_children {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val parent = launch {
launch {
log("\t\tchild1 started")
delay(1_000)
log("\t\tchild1 done")
}
launch {
log("\t\tchild2 started")
delay(1_000)
log("\t\tchild2 done")
}
delay(500)
throw RuntimeException("\tparent failed")
}
parent.join()
log("Done.")
}
}
object Failed_child_causes_cancellation_of_its_parent_and_siblings {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val parent = launch {
val child1 = launch {
log("\t\tchild1 started")
delay(500)
throw RuntimeException("child 1 failed")
}
val child2 = launch {
log("\t\tchild2 started")
delay(1_000)
log("\t\tchild2 done")
}
log("\tparent is waiting")
joinAll(child1, child2)
log("\tparent done")
}
parent.join()
log("Done.")
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/basics/B04_StructuredConcurrency.kt | 857517893 |
package com.scarlet.coroutines.basics
import com.scarlet.model.User
import com.scarlet.util.log
import kotlinx.coroutines.*
private suspend fun save(user: User) {
delay(1_000) // simulate some delay
log("User saved: $user")
}
object Launch_Demo1 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("1. before launch")
launch {
log("3. before save")
save(User("A001", "Jody", 33))
log("4. after save")
}
log("2. after launch")
}
}
object Launch_Demo2 {
@JvmStatic
fun main(args: Array<String>) {
log("0. Start")
runBlocking {
launch {
delay(1_000)
log("2. child 1 done.")
}
launch {
delay(2_000)
log("3. child 2 done.")
}
log("1. end of runBlocking")
}
log("4. Done")
}
}
object Launch_Join_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("1. start of runBlocking")
launch {
log("2. child 1 start")
delay(1_000)
log("3. child 1 done")
}
// How to print next line at the last?
log("4. Done")
}
}
// DON'T DO THIS
@DelicateCoroutinesApi
object GlobalScope_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("1. start of runBlocking")
GlobalScope.launch {
log("2. before save")
save(User("A001", "Jody", 33))
log("3. after save")
}.join()
log("4. Done.")
}
}
/**
* See what happens when you use w/ or w/o `runBlocking`, and then when use `join`.
*/
object CoroutineScope_Sneak_Preview_Demo {
@JvmStatic
fun main(args: Array<String>) {
val scope = CoroutineScope(Job())
val job = scope.launch {
log("1. before save")
save(User("A001", "Jody", 33))
log("2. after save")
}
// force the main thread wait
// Thread.sleep(2000)
// runBlocking { job.join() }
log("3. Done.")
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/basics/B02_Launch.kt | 1261114993 |
package com.scarlet.coroutines.basics
import android.annotation.SuppressLint
import com.scarlet.util.log
import com.scarlet.util.spaces
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.*
import kotlinx.coroutines.swing.Swing
import java.lang.Thread.sleep
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
data class Item(val value: String)
data class Token(val no: Int)
data class Post(val token: Token, val item: Item)
@JvmInline
private value class Data(val value: Int)
fun uiOnMain(block: () -> Unit) {
Dispatchers.Swing.asExecutor().execute(block)
}
private fun CoroutineScope.loop() {
launch {
repeat(5) {
log("${spaces(10)}Am I running?")
delay(500)
}
}
}
object UsingSyncCall {
// Blocking network request code
private fun requestToken(): Token {
log("Token request is being processed ...")
sleep(1_000) // simulate network delay
log("Token creation done")
return Token(42)
}
// Blocking network request code
private fun createPost(token: Token, item: Item): Post {
log("Post creation is being processed ...")
sleep(1_000) // simulate network delay
log("Post creation done")
return Post(token, item)
}
private fun showPost(post: Post) {
log(post)
}
private fun postItem(item: Item) {
val token = requestToken()
val post = createPost(token, item)
showPost(post)
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
loop()
postItem(Item("kiwi"))
log("Hello from main")
}
}
fun <T> background(value: T, msg: String, callback: (T) -> Unit) {
val scheduler = Executors.newSingleThreadScheduledExecutor()
// simulate network request
scheduler.schedule({
log(msg)
callback(value)
scheduler.shutdown()
}, 1_000L, TimeUnit.MILLISECONDS)
}
object UsingCallback {
private fun requestToken(callback: (Token) -> Unit) {
background(Token(42), "Token request is being processed ...", callback)
}
private fun createPost(token: Token, item: Item, callback: (Post) -> Unit) {
background(Post(token, item), "Post creation is being processed ...", callback)
}
private fun showPost(post: Post) {
log(post)
}
private fun postItem(item: Item) {
requestToken { token ->
log("Token creation done")
createPost(token, item) { post ->
log("Post creation done")
uiOnMain {
showPost(post)
}
}
}
}
@JvmStatic
fun main(args: Array<String>) = runBlocking(Dispatchers.Swing) {
loop()
postItem(Item("Kiwi"))
log("Hello from main")
}
}
object CallbackHell {
@JvmStatic
fun main(args: Array<String>) {
loadData()
}
private fun loadData() {
networkRequest { data ->
anotherRequest(data) { data1 ->
anotherRequest(data1) { data2 ->
anotherRequest(data2) { data3 ->
anotherRequest(data3) { data4 ->
anotherRequest(data4) { data5 ->
anotherRequest(data5) { data6 ->
anotherRequest(data6) { data7 ->
anotherRequest(data7) { data8 ->
anotherRequest(data8) { data9 ->
anotherRequest(data9) {
// How many more do you want?
println(it)
}
}
}
}
}
}
}
}
}
}
}
}
private fun networkRequest(block: (Data) -> Unit) {
thread {
sleep(200) // simulate network request
block(Data(0))
}
}
private fun anotherRequest(data: Data, block: (Data) -> Unit) {
thread {
sleep(200) // simulate network request
block(Data(data.value + 1))
}
}
}
object AsyncWithCompletableFuture {
private fun requestToken(): CompletableFuture<Token> = CompletableFuture.supplyAsync {
log("Token request is being processed ...")
sleep(1_000) // simulate network delay
log("Token creation done")
Token(42)
}
private fun createPost(token: Token, item: Item): CompletableFuture<Post> =
CompletableFuture.supplyAsync {
log("Post creation is being processed ...")
sleep(1_000) // simulate network delay
log("Post creation done")
Post(token, item)
// throw RuntimeException("oops")
}
private fun showPost(post: Post) {
log(post)
}
private fun postItem(item: Item) {
requestToken()
.thenCompose { token ->
createPost(token, item)
}
.thenAccept { post ->
uiOnMain {
showPost(post)
}
}
}
@JvmStatic
fun main(args: Array<String>) = runBlocking(Dispatchers.Swing) {
loop()
postItem(Item("Kiwi"))
log("Hello from main")
}
}
object AsyncWithRx {
private fun requestToken(): Observable<Token> = Observable.create { emitter ->
log("Token request is being processed ...")
sleep(1_000) // simulate network delay
log("Token creation done")
emitter.onNext(Token(42))
emitter.onComplete()
}
private fun createPost(token: Token, item: Item): Observable<Post> = Observable.create { emitter ->
log("Post creation is being processed ...")
sleep(1_000) // simulate network delay
log("Post creation done")
emitter.onNext(Post(token, item))
emitter.onComplete()
}
private fun showPost(post: Post) {
log(post)
}
@SuppressLint("CheckResult")
fun postItem(item: Item) {
requestToken()
.flatMap { token ->
createPost(token, item)
}
.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.from(Dispatchers.Swing.asExecutor()))
.subscribe { post ->
showPost(post)
}
}
@JvmStatic
fun main(args: Array<String>) = runBlocking(Dispatchers.Swing) {
loop()
postItem(Item("Kiwi"))
log("Hello from main")
}
}
object AsyncWithCoroutine {
// Suspending network request code
private suspend fun requestToken(): Token = withContext(Dispatchers.IO) {
log("Token request is being processed ...")
delay(1_000) // simulate network delay
log("Token creation done")
Token(42)
}
// Suspending network request code
private suspend fun createPost(token: Token, item: Item): Post = withContext(Dispatchers.IO) {
log("Post creation is being processed ...")
delay(1_000) // simulate network delay
log("Post creation done")
Post(token, item)
}
private fun showPost(post: Post) {
log(post)
}
private suspend fun postItem(item: Item) {
val token = requestToken()
val post = createPost(token, item)
showPost(post)
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
loop()
postItem(Item("Kiwi"))
log("Hello from main")
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/basics/B00_WhyCoroutine.kt | 2343965474 |
package com.scarlet.coroutines.basics
import com.scarlet.util.spaces
import kotlinx.coroutines.*
object Generator {
private fun fib(): Sequence<Int> = sequence {
var x = 0
var y = 1
while (true) {
println("${spaces(4)}Generates $x and waiting for next request")
yield(x)
x = y.also {
y += x
}
}
}
private fun prompt(): Boolean {
print("next? ")
return !readLine().equals("n")
}
@JvmStatic
fun main(args: Array<String>) {
val iterator = fib().iterator()
while (prompt()) {
println("Got result = ${iterator.next()}")
}
}
}
object Coroutines_Multitasking {
private suspend fun coroutine1() {
for (i in 1..10) {
println("${spaces(4)}Coroutine 1: $i")
yield()
}
}
private suspend fun coroutine2() {
for (i in 1..10) {
println("${spaces(8)}Coroutine 2: $i")
yield()
}
}
private suspend fun coroutine3() {
for (i in 1..10) {
println("${spaces(12)}Coroutine 3: $i")
yield()
}
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val job1 = launch { coroutine1() }
val job2 = launch { coroutine2() }
val job3 = launch { coroutine3() }
joinAll(job1, job2, job3)
println("Done!")
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/basics/CoroutinesDemo.kt | 4260841659 |
package com.scarlet.coroutines.advanced
import com.scarlet.util.log
import com.scarlet.util.onCompletion
import kotlinx.coroutines.*
object Canceling_Scope_Cancels_All_Children_Regardless_Of_Job_Types {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
coroutineContext.job.onCompletion("runBlocking")
// What if change to Job()
val scope = CoroutineScope(SupervisorJob())
val child1 = scope.launch {
log("child1 started")
delay(1_000)
log("child1 done")
}.onCompletion("child 1")
val child2 = scope.launch {
log("child2 started")
delay(1_000)
log("child2 done")
}.onCompletion("child 2")
delay(500)
scope.cancel()
joinAll(child1, child2)
// log("is Parent scope cancelled? = ${TODO()}")
log("is Parent job cancelled? = ${scope.coroutineContext.job.isCancelled}")
}
}
object Canceling_A_Child_Cancels_Only_The_Target_Child_Including_All_Its_Descendants_If_Any {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
// What if change to Job()
val scope = CoroutineScope(SupervisorJob())
val child1 = scope.launch {
log("child1 started")
delay(1_000)
log("child1 done")
}.onCompletion("child 1")
val child2 = scope.launch {
log("child2 started")
delay(1_000)
log("child2 done")
}.onCompletion("child 2")
delay(500)
child1.cancel()
joinAll(child1, child2)
log("is Parent cancelled? = ${scope.coroutineContext.job.isCancelled}")
}
}
object SupervisorJob_Child_Failure_SimpleDemo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
coroutineContext.job.onCompletion("runBlocking")
// What if change to Job()
val scope = CoroutineScope(SupervisorJob())
val child1 = scope.launch {
log("child1 started")
delay(500)
throw RuntimeException("child 1 failed")
}.onCompletion("child 1")
val child2 = scope.launch {
log("child2 started")
delay(1_000)
log("child2 done")
}.onCompletion("child 2")
joinAll(child1, child2)
log("is Parent cancelled? = ${scope.coroutineContext.job.isCancelled}")
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C06_SupervisorJob.kt | 2484039480 |
package com.scarlet.coroutines.advanced
import com.scarlet.util.coroutineInfo
import com.scarlet.util.log
import com.scarlet.util.onCompletion
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.swing.Swing
import java.lang.RuntimeException
import java.util.concurrent.Executors
/**
* **Coroutine Scope Functions**
*
* Unlike `async` or `launch`, the body of `coroutineScope` is called *in-place*.
* It formally creates a new coroutine, but it suspends the previous one until the new
* one is finished, so it **does not start any concurrent process**.
*
* The provided scope inherits its `coroutineContext` from the outer scope, but overrides
* the context's `Job`. This way, the produced scope respects parental responsibilities:
* - inherits a context from its parent,
* - awaits for all children before it can finish itself,
* - cancels all its children, when the parent is canceled.
*
* 1. coroutineScope
* 2. supervisorScope
* 3. withContext
* 4. withTimeout
* 5. withTimeoutOrNull
*/
object coroutineScope_Demo1 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("runBlocking: $coroutineContext")
val a = coroutineScope {
delay(1_000).also {
log("a: $coroutineContext")
}
10
}
log("a is calculated")
val b = coroutineScope {
delay(1_000).also {
log("b: $coroutineContext")
}
20
}
log("a = $a, b = $b")
}
}
object coroutineScope_Demo2 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("runBlocking begins")
coroutineScope {
log("Launching children ...")
launch {
log("child1 starts")
delay(2_000)
}.onCompletion("child1")
launch {
log("child2 starts")
delay(1_000)
}.onCompletion("child2")
delay(10)
log("Waiting until children are completed ...")
}
log("Done!")
}
}
object coroutineScope_Demo3 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("runBlocking begins")
try {
coroutineScope {
log("Launching children ...")
launch {
log("child1 starts")
delay(2_000)
}.onCompletion("child1")
launch {
log("child2 starts")
delay(1_000)
throw RuntimeException("Oops")
}.onCompletion("child2")
delay(10)
log("Waiting until children are completed ...")
}
} catch (ex: Exception) {
log("Caught exception: ${ex.javaClass.simpleName}")
}
log("Done!")
}
}
/**/
data class Details(val name: String, val followers: Int)
data class Tweet(val text: String)
class ApiException(val code: Int, message: String) : Throwable(message)
private suspend fun getFollowersNumber(): Int {
delay(100)
throw ApiException(500, "Service unavailable")
}
private suspend fun getUserName(): String {
delay(500)
return "paula abdul"
}
private suspend fun getTweets(): List<Tweet> {
delay(500)
return listOf(Tweet("Hello, world"))
}
object Not_What_We_Want {
private suspend fun getUserDetails(scope: CoroutineScope): Details {
val userName = scope.async { getUserName() }
val followersNumber = scope.async { getFollowersNumber() }
return Details(userName.await(), followersNumber.await())
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val details = try {
getUserDetails(this)
} catch (e: ApiException) {
log("Error: ${e.code}")
null
}
log("User: $details")
val tweets = async { getTweets() }
log("Tweets: ${tweets.await()}")
}
// Only Exception...
}
object What_We_Want {
private suspend fun getUserDetails(): Details = coroutineScope {
val userName = async { getUserName() }
val followersNumber = async { getFollowersNumber() }
Details(userName.await(), followersNumber.await())
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val details = try {
getUserDetails()
} catch (e: ApiException) {
log("Error: ${e.code}")
null
}
val tweets = async { getTweets() }
log("User: $details")
log("Tweets: ${tweets.await()}")
}
// User: null
// Tweets: [Tweet(text=Hello, world)]
}
object withContext_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val parent = launch(CoroutineName("parent")) {
coroutineInfo(0)
coroutineScope {
coroutineContext.job.onCompletion("coroutineScope")
log("\t\tInside coroutineScope")
coroutineInfo(1)
delay(100)
}
withContext(CoroutineName("child 1") + Dispatchers.Default) {
coroutineContext.job.onCompletion("withContext")
log("\t\tInside first withContext")
coroutineInfo(1)
delay(500)
}
Executors.newFixedThreadPool(3).asCoroutineDispatcher().use { ctx ->
withContext(CoroutineName("child 2") + ctx) {
coroutineContext.job.onCompletion("newFixedThreadPool")
log("\t\tInside second withContext")
coroutineInfo(1)
delay(1_000)
}
}
}.onCompletion("parent")
delay(50)
log("children after 50ms = ${parent.children.toList()}")
delay(200)
log("children after 250ms = ${parent.children.toList()}")
delay(600)
log("children after 850ms = ${parent.children.toList()}")
parent.join()
}
}
object MainSafety_Demo {
private suspend fun fibonacci(n: Long): Long =
withContext(Dispatchers.Default) {
fib(n).also {
log(coroutineContext)
}
}
private fun fib(n: Long): Long = if (n == 0L || n == 1L) n else fib(n - 1) + fib(n - 2)
@JvmStatic
fun main(args: Array<String>) = runBlocking {
launch(CoroutineName("parent") + Dispatchers.Swing) {
log(coroutineContext)
log("fib(40) = ${fibonacci(40)}")
}.join()
}
}
object Timeout {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
launch {
launch { // cancelled by its parent
delay(2_000)
log("Will not be printed")
}
withTimeout(1_000) { // we cancel launch
delay(1_500)
}
}.onCompletion("child 1")
launch {
delay(2_000)
log("child2 done")
}.onCompletion("child 2")
}
// (2 sec)
// Done
}
object WithTimeoutOrNull_Demo {
class User
private suspend fun fetchUser(): User {
// Runs forever
while (true) {
yield()
}
}
private suspend fun getUserOrNull(): User? =
withTimeoutOrNull(3_000) {
fetchUser()
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val user = getUserOrNull()
log("User: $user")
}
// (3 sec)
// User: null
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C08_CoroutineScopeFunctions.kt | 3920750042 |
package com.scarlet.coroutines.advanced
object Continuation_Passing_Style {
private fun add(a: Int, b: Int): Int = a + b
private fun mul(a: Double, b: Double): Double = a * b
// (1 + 2) * (3 + 4)
private fun evaluate(): Double {
// Label 0
val step1 = add(1, 2)
// Label 1
val step2 = add(3, 4)
// Label 2
val step3 = mul(step1.toDouble(), step2.toDouble())
return step3
}
@JvmStatic
fun main(args: Array<String>) {
println(evaluate())
println(fact(10))
println(
(0..10).map { fib(it.toLong()) }.joinToString(", ")
)
}
// Exercise 1: Convert this to CPS style
private fun fact(n: Long): Long =
when (n) {
0L -> 1L
else -> n * fact(n - 1)
}
// Exercise 2: Convert this to CPS style
private fun fib(n: Long): Long =
when (n) {
0L, 1L -> n
else -> fib(n - 1) + fib(n - 2)
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C02_CPS.kt | 1000355728 |
package com.scarlet.coroutines.advanced
import com.scarlet.util.log
import com.scarlet.util.onCompletion
import kotlinx.coroutines.*
import java.lang.RuntimeException
@JvmInline
private value class Image(val name: String)
private suspend fun loadImage(name: String): Image {
log("Loading ${name}: started.")
delay(1_000)
log("Loading ${name}: done.")
return Image(name)
}
private suspend fun loadImageFail(name: String): Image {
log("Loading ${name}: started.")
delay(500)
throw RuntimeException("oops")
}
private fun combineImages(image1: Image, image2: Image): Image =
Image("${image1.name} & ${image2.name}")
/**
* GlobalScope demo - not recommended.
*/
@DelicateCoroutinesApi
private suspend fun loadAndCombine(name1: String, name2: String): Image {
val deferred1 = GlobalScope.async { loadImage(name1) }.onCompletion("deferred1")
val deferred2 = GlobalScope.async { loadImage(name2) }.onCompletion("deferred2")
return combineImages(deferred1.await(), deferred2.await())
}
@DelicateCoroutinesApi
object GlobalScope_Not_Recommended {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
var image: Image? = null
val parent = GlobalScope.launch {
image = loadAndCombine("apple", "kiwi")
log("parent done.")
}.onCompletion("parent")
parent.join()
log("combined image = $image")
}
}
@DelicateCoroutinesApi
object GlobalScope_Even_If_Parent_Cancelled_Children_Keep_Going {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
var image: Image? = null
val parent = GlobalScope.launch {
image = loadAndCombine("apple", "kiwi")
log("parent done.")
}.onCompletion("parent")
delay(500)
log("Cancel parent coroutine after 500ms")
parent.cancelAndJoin()
log("combined image = $image")
delay(1_000) // To check what happens to children
}
}
@DelicateCoroutinesApi
private suspend fun loadAndCombineFail(name1: String, name2: String): Image {
val deferred1 = GlobalScope.async { loadImageFail(name1) }.onCompletion("deferred1")
val deferred2 = GlobalScope.async { loadImage(name2) }.onCompletion("deferred2")
var image1: Image?
// try {
image1 = deferred1.await() /* Actual exception will be thrown at this point! */
log("image1 = $image1")
// } catch (e: Exception) {
// log("deferred1 caught $e")
// }
val image2 = deferred2.await()
log("image2 = $image2")
return combineImages(image1 ?: Image("Oops"), image2)
}
@DelicateCoroutinesApi
object GlobalScope_EvenIf_One_Of_Children_Fails_Other_Child_Still_Runs {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
var image: Image? = null
val parent = GlobalScope.launch {
// try {
image = loadAndCombineFail("apple", "kiwi")
// } catch (e: Exception) {
// log("parent caught $e")
// }
log("parent done.")
}
parent.join()
log("combined image = $image")
delay(1_000) // To check what happens to children
}
}
/**
* Working solution 1: Pass the parent coroutine scope.
*/
object Parent_Cancellation_When_Passing_Coroutine_Scope_As_Parameter {
private suspend fun loadAndCombine(scope: CoroutineScope, name1: String, name2: String): Image {
val deferred1 = scope.async { loadImage(name1) }.onCompletion("deferred1")
val deferred2 = scope.async { loadImage(name2) }.onCompletion("deferred2")
return combineImages(deferred1.await(), deferred2.await())
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
var image: Image? = null
val parent = launch {
image = loadAndCombine(this, "apple", "kiwi")
log("Parent done")
}.onCompletion("parent")
parent.join()
// delay(500)
// log("Cancel parent coroutine after 500ms")
// parent.cancelAndJoin()
log("combined image = $image")
delay(1_000) // To check what happens to children just in case
}
}
object Child_Failure_When_Passing_Coroutine_Scope_As_Parameter {
private suspend fun loadAndCombine(scope: CoroutineScope, name1: String, name2: String): Image {
// Exception will be thrown inside `async` block, and will propagate.
val deferred1 = scope.async { loadImageFail(name1) }.onCompletion("deferred1")
val deferred2 = scope.async { loadImage(name2) }.onCompletion("deferred2")
return combineImages(deferred1.await(), deferred2.await())
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
var image: Image? = null
val parent = launch {
image = loadAndCombine(this, "apple", "kiwi")
log("Parent done")
}.onCompletion("parent")
parent.join()
log("combined image = $image")
}
}
/**
* Working solution 2 (Preferable): Use `coroutineScope()`.
*/
object Using_coroutineScope_and_when_parent_cancelled {
private suspend fun loadAndCombine(name1: String, name2: String): Image = coroutineScope {
val deferred1 = async { loadImage(name1) }.onCompletion("deferred1")
val deferred2 = async { loadImage(name2) }.onCompletion("deferred2")
combineImages(deferred1.await(), deferred2.await())
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
var image: Image? = null
val parent = launch {
image = loadAndCombine("apple", "kiwi")
log("Parent done.")
}.onCompletion("parent")
parent.join()
// delay(500)
// log("Cancel parent coroutine after 500ms")
// parent.cancelAndJoin()
log("combined image = $image")
}
}
object Using_coroutineScope_and_when_child_failed {
private suspend fun loadAndCombine(name1: String, name2: String): Image = coroutineScope {
// Exception will be thrown inside `async` block, and will rethrow.
val deferred1 = async { loadImageFail(name1) }.onCompletion("deferred1")
val deferred2 = async { loadImage(name2) }.onCompletion("deferred2")
combineImages(deferred1.await(), deferred2.await())
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
var image: Image? = null
val parent = launch {
try {
image = loadAndCombine("apple", "kiwi")
log("Parent done.")
} catch (e: Exception) {
log("parent caught $e")
}
}.onCompletion("parent")
parent.join()
log("combined image = $image")
}
}
object Using_supervisorScope_and_when_child_failed {
private suspend fun loadAndCombine(name1: String, name2: String): Image = supervisorScope {
val deferred1 = async { loadImageFail(name1) }.onCompletion("deferred1")
val deferred2 = async { loadImage(name2) }.onCompletion("deferred2")
// Exception will be thrown inside `await`, and will rethrow if not handled
// try {
combineImages(deferred1.await(), deferred2.await())
// } catch (e: Exception) {
// log("supervisorScope caught $e")
// Image("Oops")
// }
}
@JvmStatic
fun main(args: Array<String>) = runBlocking {
var image: Image? = null
val parent = launch {
try {
image = loadAndCombine("apple", "kiwi")
log("Parent done.")
} catch (e: Exception) {
log("parent caught $e")
}
}.onCompletion("parent")
parent.join()
log("combined image = $image")
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C09_ParallelDecomposition.kt | 2279884656 |
package com.scarlet.coroutines.advanced
import com.scarlet.util.*
import kotlinx.coroutines.*
/**
* When a coroutine is launched in the `CoroutineScope` of another coroutine,
* it inherits its context via `CoroutineScope.coroutineContext` and the `Job`
* of the new coroutine becomes a child of the parent coroutine's job.
*
* When the parent coroutine is cancelled, all its children are recursively cancelled,
* too. This is a very powerful feature, because it allows you to cancel all coroutines.
*/
@ExperimentalStdlibApi
object CoroutineScope_Has_Context {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val scope = CoroutineScope(Job() + CoroutineName("My Scope"))
scopeInfo(scope, 0)
// Dispatchers.Default
scope.launch(CoroutineName("Top-level Coroutine")) {
delay(100)
coroutineInfo(1)
}.join() // need to prevent early exit
}
}
object Canceling_Scope_Cancels_It_and_Its_Job {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val scope = CoroutineScope(CoroutineName("My Scope"))
// New job gets created if not provided explicitly
if (scope.coroutineContext[Job] != null) {
log("New job is created!")
}
// Dispatchers.Default
val job = scope.launch(CoroutineName("Top-level Coroutine")) {
delay(1_000)
}.onCompletion("job")
delay(500)
scope.cancel()
job.join() // why need this?
log("Done.")
}
}
object Canceling_Scope_Cancels_It_and_Its_Job_and_All_Descendants {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val scope = CoroutineScope(Job())
val parent1 = scope.launch(CoroutineName("Parent 1")) {
launch { delay(1_000); log("child 1 done") }.onCompletion("child 1")
launch { delay(1_000); log("child 2 done") }.onCompletion("child 2")
}.onCompletion("parent 1")
val parent2 = scope.launch(CoroutineName("Parent 2")) {
launch { delay(1_000); log("child 3 done") }.onCompletion("child 3")
launch { delay(1_000); log("child 4 done") }.onCompletion("child 4")
}.onCompletion("parent 2")
delay(500)
scope.cancel()
joinAll(parent1, parent2)
log("Done")
}
}
object Canceling_A_Scope_Does_Not_Affect_Its_Siblings {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val scopeLeft = CoroutineScope(Job())
val parentLeft = scopeLeft.launch(CoroutineName("Parent Left")) {
launch { delay(1_000); log("child L-1 done") }.onCompletion("child L-1")
launch { delay(1_000); log("child L-2 done") }.onCompletion("child L-2")
}.onCompletion("parent left")
val scopeRight = CoroutineScope(Job())
val parentRight = scopeRight.launch(CoroutineName("Parent Right")) {
launch { delay(1_000); log("child R-1 done") }.onCompletion("child R-1")
launch { delay(1_000); log("child R-2 done") }.onCompletion("child R-2")
}.onCompletion("parent right")
delay(500)
scopeLeft.cancel()
joinAll(parentLeft, parentRight)
log("Done")
}
}
object GlobalScope_Cancellation_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("Job for GlobalScope is ${GlobalScope.coroutineContext[Job]}")
val job = GlobalScope.launch {
launch(CoroutineName("Child 1")) { delay(100) }.onCompletion("Child 1")
launch(CoroutineName("Child 2")) { delay(1_000) }.onCompletion("Child 2")
log("GlobalScope is active")
// delay(700)
}.onCompletion("Parent")
delay(500)
log(job.children.toList().toString())
job.cancelAndJoin()
// what will happen? GlobalScope.cancel()
// GlobalScope.cancel()
}
}
object GlobalScope_Cancellation_Demo3 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("Job for GlobalScope is ${GlobalScope.coroutineContext[Job]}")
val job = GlobalScope.launch(CoroutineName("Parent")) {
launch(CoroutineName("Child 1")) { delay(1_000) }.onCompletion("Child 1")
launch(CoroutineName("Child 2")) { delay(1_000) }.onCompletion("Child 2")
log("GlobalScope is active")
// delay(700)
}.onCompletion("Parent")
GlobalScope.launch(CoroutineName("Parent 2")) {
// launch(CoroutineName("Child3")) { delay(1_000)}.onCompletion("Child 3")
delay(700)
}.onCompletion("Parent 2")
delay(500)
log(job.children.toList().toString())
job.cancelAndJoin()
// what will happen? GlobalScope.cancel()
// GlobalScope.cancel()
delay(2_000)
}
}
object GlobalScope_Cancellation_Demo4 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("Job for GlobalScope is ${GlobalScope.coroutineContext[Job]}")
val job = GlobalScope.launch(CoroutineName("Parent")) {
launch(CoroutineName("Child 1")) {
launch(CoroutineName("Grand Child")) {
delay(1_000)
}.onCompletion("Grand Child")
delay(1_000)
}.onCompletion("Child 1")
launch(CoroutineName("Child 2")) { delay(1_000) }.onCompletion("Child 2")
log("GlobalScope is active")
// delay(700)
}.onCompletion("Parent")
delay(500)
log(job.children.toList().toString())
job.cancelAndJoin()
// what will happen? GlobalScope.cancel()
// GlobalScope.cancel()
}
}
object GlobalScope_Cancellation_Demo2 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val job = launch {
launch(CoroutineName("Child 1")) { delay(1_000) }.onCompletion("Child 1")
launch(CoroutineName("Child 2")) { delay(900) }.onCompletion("Child 2")
delay(700)
log("GlobalScope is active")
}.onCompletion("Parent")
delay(500)
job.cancelAndJoin()
// what will happen? GlobalScope.cancel()
// GlobalScope.cancel()
}
}
object GlobalScope_Cancellation_Demo5 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val job = launch {
launch(CoroutineName("Child 1")) {
launch(CoroutineName("Grand Child")) {
delay(1_000)
}.onCompletion("Grand Child")
// delay(700)
}.onCompletion("Child 1")
launch(CoroutineName("Child 2")) { delay(1_000) }.onCompletion("Child 2")
}.onCompletion("Parent")
delay(500)
job.cancelAndJoin()
// what will happen? GlobalScope.cancel()
// GlobalScope.cancel()
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C04_CoroutineScope.kt | 666935034 |
package com.scarlet.coroutines.advanced
import com.scarlet.util.log
import java.util.concurrent.Executors
object Phase1 {
private fun fooWithDelay(a: Int, b: Int): Int {
log("step 1")
Thread.sleep(3_000)
log("step 2")
return a + b
}
@JvmStatic
fun main(args: Array<String>) {
log("main started")
log("result = ${fooWithDelay(3, 4)}")
log("main end")
}
}
//object Phase2
val executor = Executors.newSingleThreadScheduledExecutor {
Thread(it, "scheduler").apply { isDaemon = true }
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C10_SuspendOrigin.kt | 2567185459 |
package com.scarlet.coroutines.advanced
import com.scarlet.util.coroutineInfo
import com.scarlet.util.delim
import com.scarlet.util.log
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* CoroutineContext:
* 1. Coroutine Job
* 2. Coroutine Dispatcher
* 3. Coroutine Exception Handler
* 4. Coroutine Name
* 5. Coroutine Id (Only if debug mode is ON: -Dkotlinx.coroutines.debug)
*/
object CoroutineContext_01 {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log(Thread.currentThread().name)
log("CoroutineContext = $coroutineContext")
log("Name = ${coroutineContext[CoroutineName]}")
log("Job = ${coroutineContext[Job]}")
log("Dispatcher = ${coroutineContext[ContinuationInterceptor]}")
log("Exception handler = ${coroutineContext[CoroutineExceptionHandler]}")
}
}
object CoroutineContext_Creation_Plus {
@JvmStatic
fun main(args: Array<String>) {
// val context: CoroutineName = CoroutineName("My Coroutine")
// val context: CoroutineContext.Element = CoroutineName("My Coroutine")
var context: CoroutineContext = CoroutineName("My Coroutine")
log(context)
context += Dispatchers.Default
log(context)
context += Job()
log(context)
}
}
object CoroutineContext_Merge {
@JvmStatic
fun main(args: Array<String>) {
var context = CoroutineName("My Coroutine") + Dispatchers.Default + Job()
log(context)
delim()
/*
* Element on the right overrides the same element on the left.
*/
context += CoroutineName("Your Coroutine")
log(context)
context += Dispatchers.IO + SupervisorJob()
log(context)
delim()
/*
* Empty CoroutineContext
*/
val emptyContext = EmptyCoroutineContext
context += emptyContext
log(context)
delim()
/*
* Minus Key demo
*/
context = context.minusKey(ContinuationInterceptor)
log(context)
delim()
}
}
object CoroutineContext_Fold {
@JvmStatic
fun main(args: Array<String>) {
val context = CoroutineName("My Coroutine") + Dispatchers.Default + Job()
context.fold("") { acc, elem ->
"$acc : $elem"
}.also(::println)
context.fold(emptyList<CoroutineContext>()) { acc, elem ->
acc + elem
}.joinToString().also(::println)
}
}
object CoroutineContext_ContextInheritance_Demo {
@JvmStatic
fun main(args: Array<String>) {
log("top-level thread = ${Thread.currentThread().name}")
// The default context is an event loop on the current thread.
runBlocking(CoroutineName("Parent Coroutine: runBlocking")) {
coroutineInfo(1)
// Inherits context from parent scope. If no inherited dispatcher, use Dispatchers.DEFAULT.
launch {
// launch(CoroutineName("Child Coroutine: launch") + Dispatchers.Default) {
coroutineInfo(2)
delay(1_000)
}.join()
log("runBlocking: try to exit runBlocking")
}
log("Bye main")
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C03_Context.kt | 1062596263 |
package com.scarlet.coroutines.advanced
import com.scarlet.util.coroutineInfo
import com.scarlet.util.log
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import java.util.concurrent.Executors
import kotlin.random.Random
/**
* Dispatchers:
* 1. Dispatchers.Main
* 2. Dispatchers.IO
* 3. Dispatchers.Default
* 4. Dispatchers.Unconfined (not recommended)
*/
/**
* Exception in thread "main @coroutine#1" java.lang.IllegalStateException:
* Module with the Main dispatcher had failed to initialize.
*/
object Dispatchers_Main_Failure_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val scope = CoroutineScope(Job() + Dispatchers.Main)
scope.launch {
delay(1000)
}.join()
log("Done.")
}
}
object DefaultDispatchers_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
log("# processors = ${Runtime.getRuntime().availableProcessors()}")
repeat(20) {
launch(Dispatchers.Default) {
// To make it busy
List(1_000) { Random.nextLong() }.maxOrNull()
log("Running on thread: ${Thread.currentThread().name}")
}
}
}
}
object IODispatchers_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
repeat(64) {
launch(Dispatchers.IO) {
delay(200)
log("Running on thread: ${Thread.currentThread().name}")
}
}
}
}
/**
* IO dispatcher shares threads with a Dispatchers.Default dispatcher, so using
* withContext(Dispatchers.IO) { ... } does not lead to an actual switching to another thread.
*/
object ThreadSharing_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
launch(Dispatchers.Default) {
log("Default dispatcher: ${Thread.currentThread().name}")
withContext(Dispatchers.IO) {
log("IO dispatcher: ${Thread.currentThread().name}")
}
log("Default dispatcher: ${Thread.currentThread().name}")
}
}
}
object Unconfined_Dispatchers_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
launch(CoroutineName("Main")) {
coroutineInfo(1)
withContext(Dispatchers.Unconfined + CoroutineName("Unconfined")) {
coroutineInfo(2)
delay(1_000)
// someSuspendingFunction(Dispatchers.Default)
// Whatever thread the suspending function uses will be continue to run
coroutineInfo(2)
}
coroutineInfo(1)
}.join()
log("Done.")
}
}
private suspend fun someSuspendingFunction(dispatcher: CoroutineDispatcher) =
withContext(dispatcher) {
delay(1_000)
log("Running on thread: ${Thread.currentThread().name}")
}
/**
* newSingleThreadContext and newFixedThreadPoolContext
*/
@DelicateCoroutinesApi
object Custom_Dispatchers_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
val context = newSingleThreadContext("CustomDispatcher 1")
launch(context) {
coroutineInfo(0)
delay(100)
}.join()
context.close() // make sure to close
// Safe way
newSingleThreadContext("CustomDispatcher 2").use { ctx ->
launch(ctx) {
coroutineInfo(0)
}.join()
}
val context1 = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
launch(context1) {
coroutineInfo(0)
}.join()
context1.close() // make sure to close
/* TODO */
// Use `use` to safely close the pool
}
}
/**
* Homework: Please check `limitedParallelism` function for yourself.
* https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/limited-parallelism.html
*
* @ExperimentalCoroutinesApi
* fun limitedParallelism(parallelism: Int): CoroutineDispatcher
*/ | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C07_Dispatchers.kt | 4267145156 |
package com.scarlet.coroutines.advanced
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.concurrent.thread
import kotlin.system.measureTimeMillis
object Threads {
@JvmStatic
fun main(args: Array<String>) {
val time = measureTimeMillis {
val jobs = List(100_000) {
thread {
print(".")
Thread.sleep(1_000)
}
}
jobs.forEach { it.join() }
}
println("\nElapses time = $time ms")
}
}
object Coroutines {
@JvmStatic
fun main(args: Array<String>) = runBlocking{
val time = measureTimeMillis {
val jobs = List(100_000) {
launch {
print(".")
delay(1_000)
}
}
jobs.forEach { it.join() }
}
println("\nElapses time = $time ms")
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C01_ThreadVsCoroutine.kt | 647822753 |
package com.scarlet.coroutines.advanced
import com.scarlet.util.log
import com.scarlet.util.onCompletion
import kotlinx.coroutines.*
@DelicateCoroutinesApi
object Dependency_Between_Jobs {
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
// coroutine starts when start() or join() called
val job = launch(start = CoroutineStart.LAZY) {
log("See when I am printed ...")
delay(100)
log("Pong")
}
delay(500)
launch {
log("Ping")
job.join()
log("Ping")
}
}
}
object Jobs_Form_Coroutines_Hierarchy {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val parentJob = launch {
log("I am parent")
launch {
log("I am a child1 of the parentJob")
delay(1_000)
}.onCompletion("child1")
launch { // To check whether already finished child counted as children
log("I am child2 of the parentJob")
delay(500)
}.onCompletion("child2")
}.onCompletion("parentJob")
launch {
log("I’m a sibling of the parentJob, not its child")
delay(1_000)
}.onCompletion("sibling")
delay(300)
log("The parentJob has ${parentJob.children.count()} children")
delay(500) // By this time, another child of the parentJob should have already been completed
log("The parentJob has ${parentJob.children.count()} children")
}
}
object In_Hierarchy_Parent_Waits_Until_All_Children_Finish {
/**
* Parental responsibilities:
*
* A parent coroutine always waits for completion of all its children.
* A parent does not have to explicitly track all the children it launches,
* and it does **not** have to use `Job.join` to wait for them at the end:
*/
@JvmStatic
fun main(args: Array<String>) = runBlocking {
// launch a coroutine to process some kind of incoming request
val parent = launch {
repeat(3) { i -> // launch a few children jobs
launch { // try Dispatchers.Default
delay((i + 1) * 200L) // variable delay 200ms, 400ms, 600ms
log("\t\tChild Coroutine $i is done")
}
}
log("parent: I'm done, but will wait until all my children completes")
// No need to join here
}.onCompletion("parent: now, I am completed")
parent.join() // wait for completion of the request, including all its children
log("Done")
}
}
/**
* When a coroutine is launched in the `CoroutineScope` of another coroutine,
* it inherits its context via `CoroutineScope.coroutineContext` and the `Job`
* of the new coroutine becomes a child of the parent coroutine's job.
*
* When the parent coroutine is cancelled, all its children are recursively cancelled,
* too. However, this parent-child relation can be explicitly overridden in one
* of two ways:
*
* 1. When a _different scope is explicitly specified_ when launching a coroutine
* (for example, `GlobalScope.launch`), then it does not inherit a coroutine
* context from the original parent scope.
* 2. **When a different `Job` object is passed as the context for the new coroutine,
* then it overrides the Job of the parent scope.**
*
* In both cases, the launched coroutine is not tied to the scope it was launched
* from and operates independently.
*/
object In_Hierarchy_Parent_Waits_Until_All_Children_Finish_Other_Demo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val parentJob = launch {
log("I’m the parent")
}.onCompletion("Finally, parent finished ...")
launch(parentJob) {
log("\t\tI’m a child")
delay(1_000)
}.onCompletion("\t\tChild finished after 1000")
delay(100)
log("The Parent job has ${parentJob.children.count()} children at around 100ms")
log("is Parent active at around 100ms? ${parentJob.isActive}")
delay(500)
log("is Parent still active at around 600ms? ${parentJob.isActive}")
parentJob.join()
log("is Parent still active after joined? ${parentJob.isActive}")
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/advanced/C05_JobsRelation.kt | 1312456418 |
package com.scarlet.coroutines.android
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.snackbar.Snackbar
import com.scarlet.R
import kotlinx.coroutines.*
import java.math.BigInteger
import java.util.*
import kotlin.system.exitProcess
class MythMainActivity : AppCompatActivity() {
private lateinit var textView: TextView
private lateinit var findButton: Button
private lateinit var cancelButton: Button
private lateinit var status: TextView
private var primeJob: Job? = null
private var countingJob: Job? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_myth)
textView = findViewById(R.id.counter)
findButton = findViewById(R.id.startButton)
cancelButton = findViewById<Button>(R.id.stopButton).apply {
isEnabled = false
}
status = findViewById(R.id.findBigPrime)
findButton.setOnClickListener {
findButton.isEnabled = false
cancelButton.isEnabled = true
status.text = "Calculating big prime number ..."
showSnackbar("Launching findBigPrime ...")
primeJob = lifecycleScope.launch {
val primeNumber = findBigPrime_Wish_To_Be_NonBlocking()
// val primeNumber = findBigPrime_ProperWay()
status.text = primeNumber.toString()
findButton.isEnabled = true
cancelButton.isEnabled = false
}
}
cancelButton.setOnClickListener {
findButton.isEnabled = true
cancelButton.isEnabled = false
showSnackbar("Cancelling findBigPrime ...")
status.text = "findBigPrime cancelled"
primeJob?.cancel()
}
countingJob = lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
var value = 0
while (true) {
textView.text = value.toString().also {
value++
}
delay(1_000)
}
}
}
}
private fun showSnackbar(msg: String) {
Snackbar.make(findViewById(android.R.id.content), msg, Snackbar.LENGTH_LONG).show()
}
override fun onDestroy() {
super.onDestroy()
countingJob?.cancel()
exitProcess(0)
}
// Will this help?
private suspend fun findBigPrime_Wish_To_Be_NonBlocking(): BigInteger =
BigInteger.probablePrime(2048, Random())
private suspend fun findBigPrime_ProperWay(): BigInteger = withContext(Dispatchers.Default) {
BigInteger.probablePrime(2048, Random())
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/android/MythMainActivity.kt | 318035245 |
package com.scarlet.coroutines.android
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.scarlet.R
import kotlinx.coroutines.*
class ScopedActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val handler = CoroutineExceptionHandler { _, exception ->
Log.e(TAG, "CoroutineExceptionHandler got $exception")
}
lifecycleScope.launch {
Log.i(TAG, "parent started")
supervisorScope {
coroutineContext.job.invokeOnCompletion { ex ->
Log.e(
TAG,
"supervisorScope: isCancelled = ${coroutineContext.job.isCancelled}, cause = $ex"
)
}
launch(handler) {
Log.i(TAG, "child 1 started")
delay(2_000)
throw RuntimeException("OOPS!")
}.apply {
invokeOnCompletion {
Log.i(TAG, "Child 1: isCancelled = $isCancelled, cause = $it")
}
}
launch {
Log.i(TAG, "child 2 started")
delay(5_000)
}.apply {
invokeOnCompletion {
Log.i(TAG, "Child2: isCancelled = $isCancelled, cause = $it")
}
}
Log.i(TAG, "inside subScope... ")
}
}.apply {
invokeOnCompletion {
Log.i(TAG, "Parent: isCancelled = $isCancelled, cause = $it")
}
}
}
override fun onStart() {
super.onStart()
Log.d(TAG, "[onStart]")
}
override fun onStop() {
super.onStop()
Log.d(TAG, "[onStop]")
}
override fun onPause() {
super.onPause()
Log.d(TAG, "[onPause]")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "[onResume]")
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "[onDestroy]")
}
companion object {
const val TAG = "Scoped"
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/android/ScopedActivity.kt | 3736325392 |
package com.scarlet.coroutines.android.livedata
import androidx.lifecycle.*
import com.scarlet.model.Article
import com.scarlet.util.Resource
import kotlinx.coroutines.*
import java.lang.IllegalArgumentException
class ArticleViewModel(
private val apiService: ApiService
) : ViewModel() {
/**
* Style 1
*/
private val _articles = MutableLiveData<Resource<List<Article>>>()
val articles: LiveData<Resource<List<Article>>> = _articles
init {
viewModelScope.launch {
_articles.value = apiService.getArticles()
}
}
/**
* Style 2: Use MutableLiveData and apply
*/
// val articles: LiveData<Resource<List<Article>>> =
// MutableLiveData<Resource<List<Article>>>().apply {
// viewModelScope.launch {
// value = apiService.getArticles()
// }
// }
/**
* Style 3: Use liveData builder
*/
// val articles: LiveData<Resource<List<Article>>> = liveData {
// emit(apiService.getArticles())
// }
/**
* The block starts executing when the returned LiveData becomes active.
*/
val topArticle: LiveData<Resource<Article>> = liveData {
while (true) {
emit(apiService.getTopArticle())
delay(FETCH_INTERVAL)
}
}
@Suppress("UNCHECKED_CAST")
val articlesByTopAuthor: LiveData<Resource<List<Article>>> =
topArticle
.switchMap { resource ->
when (resource) {
is Resource.Success<Article> ->
liveData {
emit(Resource.Loading)
emitSource(apiService.getArticlesByAuthorName(resource.data?.author!!))
}
else ->
liveData {
emit(resource as Resource<List<Article>>)
}
}
}
companion object {
const val FETCH_INTERVAL = 5_000L
}
}
@Suppress("UNCHECKED_CAST")
class ArticleViewModelFactory() : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (!modelClass.isAssignableFrom(ArticleViewModel::class.java))
throw IllegalArgumentException("No such viewmodel")
return ArticleViewModel(FakeApiService()) as T
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/android/livedata/ArticleViewModel.kt | 1488788166 |
package com.scarlet.coroutines.android.livedata
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.scarlet.R
class ArticleActivity : AppCompatActivity() {
private val viewModel: ArticleViewModel by viewModels { ArticleViewModelFactory() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel.topArticle.observe(this) {
Log.v(TAG, "topArticle: $it")
}
viewModel.articlesByTopAuthor.observe(this) {
Log.w(TAG, "articlesByTopAuthor: $it")
}
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart: ")
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop: ")
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause: ")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume: ")
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy:")
}
companion object {
private const val TAG = "Article"
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/android/livedata/ArticleActivity.kt | 3893676871 |
package com.scarlet.coroutines.android.livedata
import androidx.lifecycle.LiveData
import androidx.lifecycle.liveData
import com.scarlet.model.Article
import com.scarlet.model.Recipe
import com.scarlet.util.Resource
class FakeApiService : ApiService {
override suspend fun getArticles(): Resource<List<Article>> {
return Resource.Success(Recipe.mRecipes) as Resource<List<Article>>
}
override suspend fun getTopArticle(): Resource<Article> {
val random: Int = (0..Article.articleSamples.size).random()
return Resource.Success(Article.articleSamples[random]) as Resource<Article>
}
override fun getArticlesByAuthorName(name: String): LiveData<Resource<List<Article>>> =
liveData {
emit(Resource.Success(Article.articleSamples.filter { it.author == name }))
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/android/livedata/FakeApiService.kt | 2114012333 |
package com.scarlet.coroutines.android.livedata
import androidx.lifecycle.LiveData
import com.scarlet.model.Article
import com.scarlet.util.Resource
interface ApiService {
/**
* Get all articles
*/
suspend fun getArticles(): Resource<List<Article>>
/**
* Get the most recommended (i.e., top-ranked) article
*/
suspend fun getTopArticle(): Resource<Article>
/**
* Get all the articles written by a specific author
*/
fun getArticlesByAuthorName(name: String): LiveData<Resource<List<Article>>>
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/android/livedata/ApiService.kt | 3396753417 |
package com.scarlet.coroutines.android
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.coroutineScope
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.scarlet.R
import com.scarlet.model.Recipe
import com.scarlet.model.Recipe.Companion.mRecipes
import com.scarlet.util.Resource
import com.scarlet.util.spaces
import kotlinx.coroutines.*
import java.util.LinkedHashMap
@ExperimentalCoroutinesApi
class CoActivity : AppCompatActivity() {
private val apiService = FakeRemoteDataSource()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
prepareFakeData()
Log.d(TAG, "[onCreate] massive launching started ...")
/*
* Use either `lifecycleScope` or `lifecycle.coroutineScope`
*/
lifecycle.coroutineScope.launch {
Log.d(TAG, "launch started")
val recipes = apiService.getRecipes()
Log.d(TAG, "recipes in launch = $recipes")
}.invokeOnCompletion {
Log.d(TAG, "launch completed: $it")
}
lifecycleScope.launchWhenCreated {
Log.d(TAG, "launchWhenCreated started")
val recipes = apiService.getRecipes()
Log.d(TAG, "recipes in launchWhenCreated = $recipes")
}.invokeOnCompletion {
Log.d(TAG, "launchWhenCreated completed: $it")
}
lifecycleScope.launchWhenStarted {
Log.d(TAG, "${spaces(2)}launchWhenStarted started")
val recipes = apiService.getRecipes()
Log.d(TAG, "${spaces(2)}recipes in launchWhenStarted = $recipes")
}.invokeOnCompletion {
Log.d(TAG, "${spaces(2)}launchWhenStarted completed: $it")
}
lifecycleScope.launchWhenResumed {
Log.d(TAG, "${spaces(4)}launchWhenResumed started")
val recipes = apiService.getRecipes()
Log.d(TAG, "${spaces(4)}recipes in launchWhenResumed = $recipes")
}.invokeOnCompletion {
Log.d(TAG, "${spaces(4)}launchWhenResumed completed: $it")
}
lifecycleScope.launch {
Log.d(TAG, "repeatOnLifecycle launched")
lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
Log.d(TAG, "${spaces(4)}repeatOnLifeCycle at RESUMED started")
val recipes = apiService.getRecipes()
Log.d(TAG, "${spaces(4)}recipes in repeatOnLifeCycle = $recipes")
}
Log.d(TAG, "See when i am printed ...")
}.invokeOnCompletion {
Log.d(TAG, "launch for repeatOnLifeCycle completed: $it")
}
}
private fun prepareFakeData() {
FakeRemoteDataSource.FAKE_NETWORK_DELAY = 3_000
apiService.addRecipes(mRecipes)
}
override fun onStart() {
super.onStart()
Log.d(TAG, "[onStart]")
}
override fun onStop() {
super.onStop()
Log.d(TAG, "[onStop]")
}
override fun onPause() {
super.onPause()
Log.d(TAG, "[onPause]")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "[onResume]")
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "[onDestroy]")
}
companion object {
const val TAG = "Coroutine"
}
private class FakeRemoteDataSource {
private val mRecipes: MutableMap<String, Recipe> = LinkedHashMap<String, Recipe>()
suspend fun getRecipes(): Resource<List<Recipe>> {
return withContext(Dispatchers.IO) {
delay(FAKE_NETWORK_DELAY)
Resource.Success(mRecipes.values.toList())
}
}
fun addRecipes(recipes: List<Recipe>) {
recipes.forEach { recipe -> mRecipes[recipe.recipeId] = recipe.copy() }
}
companion object {
var FAKE_NETWORK_DELAY = 0L
}
}
}
| KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/android/CoActivity.kt | 3530475536 |
package com.scarlet.coroutines.migration
import com.scarlet.model.Recipe
import com.scarlet.util.Resource
import kotlinx.coroutines.suspendCancellableCoroutine
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
interface RecipeApi {
@GET("api/search")
fun search(
@Query("key") key: String,
@Query("q") query: String
): Call<List<Recipe>>
}
interface RecipeCallback<T> {
fun onSuccess(response: Resource<T>)
fun onError(response: Resource<T>)
}
object UsingCallback_Demo2 {
fun searchRecipes(
query: String, api: RecipeApi, callback: RecipeCallback<List<Recipe>>
) {
val call = api.search("key", query)
call.enqueue(object : Callback<List<Recipe>> {
override fun onResponse(call: Call<List<Recipe>>, response: Response<List<Recipe>>) {
if (response.isSuccessful) {
callback.onSuccess(Resource.Success(response.body()!!))
} else {
callback.onError(Resource.Error(response.message()))
}
}
override fun onFailure(call: Call<List<Recipe>>, t: Throwable) {
callback.onError(Resource.Error(t.message))
}
})
}
}
object CvtToSuspendingFunction_Demo2 {
fun searchRecipes(
query: String, api: RecipeApi, callback: RecipeCallback<List<Recipe>>
) {
val call = api.search("key", query)
call.enqueue(object : Callback<List<Recipe>> {
override fun onResponse(call: Call<List<Recipe>>, response: Response<List<Recipe>>) {
if (response.isSuccessful) {
callback.onSuccess(Resource.Success(response.body()!!))
} else {
callback.onError(Resource.Error(response.message()))
}
}
override fun onFailure(call: Call<List<Recipe>>, t: Throwable) {
callback.onError(Resource.Error(t.message))
}
})
}
// Use Call.await()
suspend fun searchRecipesV2(query: String, api: RecipeApi): Resource<List<Recipe>> {
val call: Call<List<Recipe>> = api.search("key", query)
TODO()
}
}
suspend fun <T> Call<T>.await(): T = suspendCancellableCoroutine { continuation ->
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
if (response.isSuccessful) {
continuation.resume(response.body()!!)
} else {
continuation.resumeWithException(Throwable(response.message()))
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
continuation.invokeOnCancellation {
cancel()
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/migration/M02_CvtCallbackToSuspendFun2.kt | 3400749728 |
package com.scarlet.coroutines.migration
import com.scarlet.util.log
import kotlinx.coroutines.runBlocking
import java.io.IOException
// Callback
private interface AsyncCallback {
fun onSuccess(result: String)
fun onError(ex: Exception)
}
object UsingCallback_Demo1 {
// Method using callback to simulate a long running task
private fun getData(callback: AsyncCallback, status: Boolean = true) {
// Do network request here, and then respond accordingly
if (status) {
callback.onSuccess("[Beep.Boop.Beep]")
} else {
callback.onError(IOException("Network failure"))
}
}
@JvmStatic
fun main(args: Array<String>) {
getData(object : AsyncCallback {
override fun onSuccess(result: String) {
log("Data received: $result")
}
override fun onError(ex: Exception) {
log("Caught ${ex.javaClass.simpleName}")
}
}, true) // for success case
getData(object : AsyncCallback {
override fun onSuccess(result: String) {
log("Data received: $result")
}
override fun onError(ex: Exception) {
log("Caught ${ex.javaClass.simpleName}")
}
}, false) // for error case
}
}
object CvtToSuspendingFunction_Demo1 {
// Use resume/resumeWithException or resumeWith only
private suspend fun getData(status: Boolean = true): String = TODO()
@JvmStatic
fun main(args: Array<String>) = runBlocking<Unit> {
// for success case
getData(true).also {
log("Data received: $it")
}
// for error case
try {
getData(false)
} catch (ex: Exception) {
log("Caught ${ex.javaClass.simpleName}")
}
}
} | KotlinCoroutines-demo/app/src/main/java/com/scarlet/coroutines/migration/M01_CvtCallbackToSuspendFun1.kt | 886433233 |
package com.example.platform_channels_battery
import androidx.annotation.NonNull // Importe esta linha
import io.flutter.embedding.engine.FlutterEngine // Importe esta linha
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.MethodChannel // Importe esta linha
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
class MainActivity: FlutterActivity() {
private val CHANNEL = "samples.flutter.dev/battery"
/**
* Configura o mecanismo FlutterEngine para suportar a comunicação entre o código Dart e o código nativo (Kotlin/Java).
* Um canal de comunicação é criado com o nome "samples.flutter.dev/battery".
* O método setMethodCallHandler é utilizado para definir um manipulador de chamadas de método, onde o código nativo
* responde às mensagens enviadas pelo Dart. Neste caso, o código nativo responde à chamada do método "getBatteryLevel".
* Se a mensagem for reconhecida, o nível da bateria é retornado com sucesso para o Dart; caso contrário, um erro é enviado de volta.
*/
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// Cria um canal de comunicação entre o código Dart e o código nativo (Kotlin/Java).
// O nome do canal é "samples.flutter.dev/battery".
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
// Este bloco de código é chamado quando o Dart envia uma mensagem para o canal.
// Verifica se a mensagem do Dart é para obter o nível da bateria.
if (call.method == "getBatteryLevel") {
val batteryLevel = getBatteryLevel()
if (batteryLevel != -1) {
result.success(batteryLevel)
} else {
// Se não for bem-sucedido, envia um erro de volta para o Dart.
result.error("UNAVAILABLE", "Battery level not available.", null)
}
} else {
// Se a mensagem do Dart não for reconhecida, informa que não foi implementada.
result.notImplemented()
}
}
}
// Função para obter o nível da bateria.
private fun getBatteryLevel(): Int {
// Declara uma variável para armazenar o nível da bateria.
val batteryLevel: Int
// Verifica a versão do Android para escolher o método
// adequado para obter o nível da bateria.
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
// Se a versão for igual ou superior ao Android Lollipop, usa a API BatteryManager.
val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
// Se a versão for inferior ao Android Lollipop, usa a Intent ACTION_BATTERY_CHANGED.
val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
}
// Retorna o nível da bateria.
return batteryLevel
}
}
| flutter_platform_channel_battery/android/app/src/main/kotlin/com/example/platform_channels_battery/MainActivity.kt | 5804808 |
package com.ujizin.camposer
object Config {
const val compileSdk = 33
const val targetSdk = 33
const val minSdk = 21
const val versionCode = 8
const val versionName = "0.3.2"
const val groupId = "io.github.ujizin"
const val artifactId = "camposer"
}
| camerajetpackcompose/buildSrc/src/main/kotlin/ujizin/camposer/Config.kt | 1072860304 |
package com.ujizin.sample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.ujizin.sample.feature.camera.CameraScreen
import com.ujizin.sample.feature.configuration.ConfigurationScreen
import com.ujizin.sample.feature.gallery.GalleryScreen
import com.ujizin.sample.feature.permission.AppPermission
import com.ujizin.sample.feature.preview.PreviewScreen
import com.ujizin.sample.router.Args
import com.ujizin.sample.router.Router
import com.ujizin.sample.router.navigate
import com.ujizin.sample.router.route
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
setContent {
CamposerTheme {
AppPermission {
val navHost = rememberNavController()
NavGraph(navHost)
}
}
}
}
@Composable
fun NavGraph(navHost: NavHostController) {
NavHost(navHost, startDestination = Router.Camera.route) {
route(Router.Camera) {
CameraScreen(
onGalleryClick = { navHost.navigate(Router.Gallery) },
onConfigurationClick = { navHost.navigate(Router.Configuration) }
)
}
route(Router.Gallery) {
GalleryScreen(
onBackPressed = { navHost.navigateUp() },
onPreviewClick = { navHost.navigate(Router.Preview.createRoute(it)) }
)
}
route(Router.Configuration) {
ConfigurationScreen(onBackPressed = { navHost.navigateUp() })
}
route(
route = Router.Preview,
arguments = listOf(
navArgument(Args.Path) { type = NavType.StringType },
)
) {
PreviewScreen(onBackPressed = { navHost.navigateUp() })
}
}
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/MainActivity.kt | 928385184 |
package com.ujizin.sample.di
import com.ujizin.sample.feature.camera.CameraViewModel
import com.ujizin.sample.data.local.datasource.FileDataSource
import com.ujizin.sample.data.local.datasource.UserDataSource
import com.ujizin.sample.data.local.UserStore
import com.ujizin.sample.data.local.UserStoreImpl
import com.ujizin.sample.data.mapper.UserMapper
import com.ujizin.sample.feature.configuration.ConfigurationViewModel
import com.ujizin.sample.feature.gallery.GalleryViewModel
import com.ujizin.sample.feature.preview.PreviewViewModel
import kotlinx.serialization.json.Json
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
object Modules {
val localStores = module {
factory<UserStore> {
UserStoreImpl(get(), Json)
}
}
val mappers = module {
factory { UserMapper() }
}
val dataSources = module {
factory { FileDataSource() }
factory { UserDataSource(get(), get()) }
}
val viewModels = module {
viewModel { CameraViewModel(get(), get()) }
viewModel { GalleryViewModel(get()) }
viewModel { ConfigurationViewModel(get()) }
viewModel { PreviewViewModel(get()) }
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/di/Modules.kt | 1498118073 |
package com.ujizin.sample
import android.app.Application
import com.ujizin.sample.di.Modules
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@SampleApplication)
modules(
Modules.localStores,
Modules.mappers,
Modules.dataSources,
Modules.viewModels,
)
}
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/SampleApplication.kt | 2370798693 |
package com.ujizin.sample.extensions
import java.util.Locale
internal fun Float.roundTo(n: Int): Float {
return try {
"%.${n}f".format(Locale.US, this).toFloat()
} catch (e: NumberFormatException) {
this
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/extensions/FloatExtensions.kt | 4062072261 |
package com.ujizin.sample.extensions
val Int.minutes get() = (this / 60).toString().padStart(2, '0')
val Int.seconds get() = (this % 60).toString().padStart(2, '0') | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/extensions/IntExtensions.kt | 2954520345 |
package com.ujizin.sample.extensions
import androidx.annotation.WorkerThread
import androidx.camera.core.ImageProxy
import com.google.zxing.BinaryBitmap
import com.google.zxing.MultiFormatReader
import com.google.zxing.NotFoundException
import com.google.zxing.PlanarYUVLuminanceSource
import com.google.zxing.common.HybridBinarizer
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.nio.ByteBuffer
fun ByteBuffer.toByteArray(): ByteArray {
rewind()
val data = ByteArray(remaining())
get(data)
return data
}
@WorkerThread
suspend fun MultiFormatReader.getQRCodeResult(
image: ImageProxy,
dispatcher: CoroutineDispatcher = Dispatchers.IO
) = withContext(dispatcher) {
with(image) {
val data = planes.firstOrNull()?.buffer?.toByteArray()
val source = PlanarYUVLuminanceSource(data, width, height, 0, 0, width, height, false)
val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
try {
decode(binaryBitmap)
} catch (e: NotFoundException) {
e.printStackTrace()
null
}
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/extensions/ReaderExtensions.kt | 3466533444 |
package com.ujizin.sample.extensions
import android.app.RecoverableSecurityException
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.annotation.WorkerThread
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.DurationUnit
@WorkerThread
suspend fun File.getDuration(context: Context): Int? = withContext(Dispatchers.IO) {
if (isVideo) {
val retriever = MediaMetadataRetriever()
try {
retriever.run {
setDataSource(context, Uri.fromFile(this@getDuration))
extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
?.toLongOrNull()
?.milliseconds?.toInt(DurationUnit.SECONDS)
}
} catch (e: Exception) {
null
}
} else null
}
fun File.getExternalUri(contentResolver: ContentResolver): Uri? {
val projection = arrayOf(MediaStore.MediaColumns._ID)
val selection = MediaStore.MediaColumns.DATA + "=?"
val selectionArgs = arrayOf(absolutePath)
val filesUri = MediaStore.Files.getContentUri("external")
return contentResolver.query(
filesUri,
projection,
selection,
selectionArgs,
null
)?.use { cursor ->
val id = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)
if (cursor.moveToFirst()) {
return@use ContentUris.withAppendedId(
when {
isVideo -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
else -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
},
cursor.getLong(id)
)
}
null
}
}
val File.isVideo: Boolean get() = extension == "mp4"
@WorkerThread
suspend fun File.delete(
contentResolver: ContentResolver,
intentSenderLauncher: ActivityResultLauncher<IntentSenderRequest>,
dispatcher: CoroutineDispatcher = Dispatchers.IO,
) = withContext(dispatcher) {
val uri = getExternalUri(contentResolver) ?: return@withContext
try {
contentResolver.delete(uri, null, null)
} catch (e: SecurityException) {
val intentSender = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
MediaStore.createDeleteRequest(contentResolver, listOf(uri)).intentSender
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
val recoverySecurityException = e as? RecoverableSecurityException
recoverySecurityException?.userAction?.actionIntent?.intentSender
}
else -> null
}
intentSender?.let { sender ->
intentSenderLauncher.launch(IntentSenderRequest.Builder(sender).build())
}
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/extensions/FileExtensions.kt | 1038476590 |
package com.ujizin.sample.extensions
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
/**
* Observe lifecycle as state composable.
*
* Based on https://stackoverflow.com/a/69061897/11903815.
* */
@Composable
fun Lifecycle.observeAsState(): State<Lifecycle.Event> {
val state = remember { mutableStateOf(Lifecycle.Event.ON_ANY) }
DisposableEffect(this) {
val observer = LifecycleEventObserver { _, event ->
state.value = event
}
[email protected](observer)
onDispose {
[email protected](observer)
}
}
return state
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/extensions/LifecycleExtensions.kt | 789764534 |
package com.ujizin.sample.extensions
fun String.capitalize() = replaceFirstChar { it.uppercase() } | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/extensions/StringExtensions.kt | 3736257866 |
package com.ujizin.sample.extensions
import androidx.compose.foundation.clickable
import androidx.compose.ui.Modifier
fun Modifier.noClickable() = then(Modifier.clickable(enabled = false) {}) | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/extensions/ModifierExtensions.kt | 2871775645 |
package com.ujizin.sample.components
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import com.ujizin.sample.R
@Composable
fun Section(
modifier: Modifier = Modifier,
title: @Composable () -> Unit,
onBackPressed: () -> Unit,
content: @Composable (PaddingValues) -> Unit,
) {
Scaffold(
modifier = modifier,
topBar = {
TopAppBar(
contentColor = Color.White,
title = { title() },
navigationIcon = {
NavigationIcon(
icon = Icons.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.back),
onClick = onBackPressed,
)
},
)
},
) { content(it) }
}
@Composable
fun NavigationIcon(
modifier: Modifier = Modifier,
icon: ImageVector,
contentDescription: String,
onClick: () -> Unit,
) {
IconButton(modifier = modifier, onClick = onClick) {
Icon(
imageVector = icon,
contentDescription = contentDescription,
tint = Color.White,
)
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/components/Section.kt | 1257822446 |
package com.ujizin.sample.feature.configuration
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ujizin.sample.data.local.datasource.UserDataSource
import com.ujizin.sample.domain.User
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
class ConfigurationViewModel(
private val userDataSource: UserDataSource,
) : ViewModel() {
private val _uiState: MutableStateFlow<ConfigurationUiState> = MutableStateFlow(
value = ConfigurationUiState.Initial
)
val uiState = _uiState.asStateFlow()
init {
getUser()
}
private fun getUser() {
viewModelScope.launch {
userDataSource.getUser()
.onStart { ConfigurationUiState.Initial }
.catch {
Log.e(
this::class.java.name,
"Error on load user configuration: ${it.message}"
)
}
.collect { _uiState.emit(ConfigurationUiState.Success(it)) }
}
}
fun updateUser(user: User) {
viewModelScope.launch {
userDataSource.updateUser(user)
_uiState.update { ConfigurationUiState.Success(user) }
}
}
}
sealed interface ConfigurationUiState {
object Initial : ConfigurationUiState
data class Success(val user: User) : ConfigurationUiState
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/configuration/ConfigurationViewModel.kt | 2577320310 |
package com.ujizin.sample.feature.configuration
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Switch
import androidx.compose.material.SwitchDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ujizin.sample.R
import com.ujizin.sample.components.Section
import com.ujizin.sample.domain.User
import org.koin.androidx.compose.get
@Composable
fun ConfigurationScreen(
viewModel: ConfigurationViewModel = get(),
onBackPressed: () -> Unit,
) {
Section(
title = {
Text(stringResource(id = R.string.configuration).replaceFirstChar { it.uppercase() })
},
onBackPressed = onBackPressed,
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
when (val result: ConfigurationUiState = uiState) {
ConfigurationUiState.Initial -> Box {}
is ConfigurationUiState.Success -> {
ConfigurationSection(result.user) { updateUser ->
viewModel.updateUser(updateUser)
}
}
}
}
}
@Composable
private fun ConfigurationSection(user: User, onConfigurationChange: (User) -> Unit) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
ConfigurationOption(
text = stringResource(id = R.string.configuration_cam_selector),
checked = user.useCamFront,
onCheckedChange = { onConfigurationChange(user.copy(useCamFront = !user.useCamFront)) }
)
ConfigurationOption(
text = stringResource(id = R.string.configuration_pinch_to_zoom),
checked = user.usePinchToZoom,
onCheckedChange = { onConfigurationChange(user.copy(usePinchToZoom = !user.usePinchToZoom)) }
)
ConfigurationOption(
text = stringResource(id = R.string.configuration_tap_to_focus),
checked = user.useTapToFocus,
onCheckedChange = { onConfigurationChange(user.copy(useTapToFocus = !user.useTapToFocus)) }
)
}
}
@Composable
private fun ConfigurationOption(
text: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(text = text.replaceFirstChar { it.uppercase() })
Switch(
checked = checked,
onCheckedChange = onCheckedChange,
colors = SwitchDefaults.colors(
checkedThumbColor = MaterialTheme.colors.primary
)
)
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/configuration/ConfigurationScreen.kt | 1471896740 |
package com.ujizin.sample.feature.camera
import android.widget.Toast
import androidx.camera.core.ImageProxy
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.skydoves.cloudy.Cloudy
import com.ujizin.camposer.CameraPreview
import com.ujizin.camposer.state.CamSelector
import com.ujizin.camposer.state.CameraState
import com.ujizin.camposer.state.rememberCamSelector
import com.ujizin.camposer.state.rememberCameraState
import com.ujizin.camposer.state.rememberFlashMode
import com.ujizin.camposer.state.rememberImageAnalyzer
import com.ujizin.camposer.state.rememberTorch
import com.ujizin.sample.extensions.noClickable
import com.ujizin.sample.feature.camera.components.ActionBox
import com.ujizin.sample.feature.camera.components.BlinkPictureBox
import com.ujizin.sample.feature.camera.components.SettingsBox
import com.ujizin.sample.feature.camera.mapper.toFlash
import com.ujizin.sample.feature.camera.mapper.toFlashMode
import com.ujizin.sample.feature.camera.model.CameraOption
import com.ujizin.sample.feature.camera.model.Flash
import org.koin.androidx.compose.get
import java.io.File
@Composable
fun CameraScreen(
viewModel: CameraViewModel = get(),
onGalleryClick: () -> Unit,
onConfigurationClick: () -> Unit,
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
when (val result: CameraUiState = uiState) {
is CameraUiState.Ready -> {
val cameraState = rememberCameraState()
CameraSection(
cameraState = cameraState,
useFrontCamera = result.user.useCamFront,
usePinchToZoom = result.user.usePinchToZoom,
useTapToFocus = result.user.useTapToFocus,
lastPicture = result.lastPicture,
qrCodeText = result.qrCodeText,
onGalleryClick = onGalleryClick,
onConfigurationClick = onConfigurationClick,
onRecording = { viewModel.toggleRecording(cameraState) },
onTakePicture = { viewModel.takePicture(cameraState) },
onAnalyzeImage = viewModel::analyzeImage
)
val context = LocalContext.current
LaunchedEffect(result.throwable) {
if (result.throwable != null) {
Toast.makeText(context, result.throwable.message, Toast.LENGTH_SHORT).show()
}
}
}
CameraUiState.Initial -> Unit
}
}
@Composable
fun CameraSection(
cameraState: CameraState,
useFrontCamera: Boolean,
usePinchToZoom: Boolean,
useTapToFocus: Boolean,
qrCodeText: String?,
lastPicture: File?,
onTakePicture: () -> Unit,
onRecording: () -> Unit,
onGalleryClick: () -> Unit,
onAnalyzeImage: (ImageProxy) -> Unit,
onConfigurationClick: () -> Unit,
) {
var flashMode by cameraState.rememberFlashMode()
var camSelector by rememberCamSelector(if (useFrontCamera) CamSelector.Front else CamSelector.Back)
var zoomRatio by rememberSaveable { mutableStateOf(cameraState.minZoom) }
var zoomHasChanged by rememberSaveable { mutableStateOf(false) }
val hasFlashUnit by rememberUpdatedState(cameraState.hasFlashUnit)
var cameraOption by rememberSaveable { mutableStateOf(CameraOption.Photo) }
val isRecording by rememberUpdatedState(cameraState.isRecording)
var enableTorch by cameraState.rememberTorch(initialTorch = false)
val imageAnalyzer = cameraState.rememberImageAnalyzer(analyze = onAnalyzeImage)
CameraPreview(
cameraState = cameraState,
camSelector = camSelector,
captureMode = cameraOption.toCaptureMode(),
enableTorch = enableTorch,
flashMode = flashMode,
zoomRatio = zoomRatio,
imageAnalyzer = imageAnalyzer,
isPinchToZoomEnabled = usePinchToZoom,
isFocusOnTapEnabled = useTapToFocus,
onZoomRatioChanged = {
zoomHasChanged = true
zoomRatio = it
},
onSwitchToFront = { bitmap ->
Cloudy(radius = 20) { Image(bitmap.asImageBitmap(), contentDescription = null) }
},
onSwitchToBack = { bitmap ->
Cloudy(radius = 20) { Image(bitmap.asImageBitmap(), contentDescription = null) }
}
) {
BlinkPictureBox(lastPicture, cameraOption == CameraOption.Video)
CameraInnerContent(
Modifier.fillMaxSize(),
zoomHasChanged = zoomHasChanged,
zoomRatio = zoomRatio,
flashMode = flashMode.toFlash(enableTorch),
isRecording = isRecording,
cameraOption = cameraOption,
hasFlashUnit = hasFlashUnit,
qrCodeText = qrCodeText,
isVideoSupported = cameraState.isVideoSupported,
onFlashModeChanged = { flash ->
enableTorch = flash == Flash.Always
flashMode = flash.toFlashMode()
},
onZoomFinish = { zoomHasChanged = false },
lastPicture = lastPicture,
onTakePicture = onTakePicture,
onRecording = onRecording,
onSwitchCamera = {
if (cameraState.isStreaming) {
camSelector = camSelector.inverse
}
},
onCameraOptionChanged = { cameraOption = it },
onGalleryClick = onGalleryClick,
onConfigurationClick = onConfigurationClick
)
}
}
@Composable
fun CameraInnerContent(
modifier: Modifier = Modifier,
zoomHasChanged: Boolean,
zoomRatio: Float,
flashMode: Flash,
isRecording: Boolean,
cameraOption: CameraOption,
hasFlashUnit: Boolean,
qrCodeText: String?,
lastPicture: File?,
isVideoSupported: Boolean,
onGalleryClick: () -> Unit,
onFlashModeChanged: (Flash) -> Unit,
onZoomFinish: () -> Unit,
onRecording: () -> Unit,
onTakePicture: () -> Unit,
onConfigurationClick: () -> Unit,
onSwitchCamera: () -> Unit,
onCameraOptionChanged: (CameraOption) -> Unit,
) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.SpaceBetween,
) {
SettingsBox(
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp, bottom = 8.dp, start = 24.dp, end = 24.dp),
flashMode = flashMode,
zoomRatio = zoomRatio,
isVideo = cameraOption == CameraOption.Video,
hasFlashUnit = hasFlashUnit,
zoomHasChanged = zoomHasChanged,
isRecording = isRecording,
onFlashModeChanged = onFlashModeChanged,
onConfigurationClick = onConfigurationClick,
onZoomFinish = onZoomFinish,
)
ActionBox(
modifier = Modifier
.fillMaxWidth()
.noClickable()
.padding(bottom = 32.dp, top = 16.dp),
lastPicture = lastPicture,
onGalleryClick = onGalleryClick,
cameraOption = cameraOption,
qrCodeText = qrCodeText,
onTakePicture = onTakePicture,
isRecording = isRecording,
isVideoSupported = isVideoSupported,
onRecording = onRecording,
onSwitchCamera = onSwitchCamera,
onCameraOptionChanged = onCameraOptionChanged,
)
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/CameraScreen.kt | 2904751116 |
package com.ujizin.sample.feature.camera.mapper
import com.ujizin.camposer.state.FlashMode
import com.ujizin.sample.feature.camera.model.Flash
fun Flash.toFlashMode() = when (this) {
Flash.Auto -> FlashMode.Auto
Flash.On -> FlashMode.On
Flash.Off, Flash.Always -> FlashMode.Off
}
fun FlashMode.toFlash(isTorchEnabled: Boolean) = when (this) {
FlashMode.On -> Flash.On
FlashMode.Auto -> Flash.Auto
FlashMode.Off -> Flash.Off
}.takeIf { !isTorchEnabled } ?: Flash.Always
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/mapper/FlashMapper.kt | 3663207165 |
package com.ujizin.sample.feature.camera.components
import androidx.compose.animation.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.ujizin.sample.extensions.minutes
import com.ujizin.sample.extensions.seconds
import kotlinx.coroutines.delay
@Composable
fun VideoBox(
modifier: Modifier = Modifier,
isRecording: Boolean,
) {
var timer by remember { mutableStateOf(0) }
var lastTimer by remember { mutableStateOf(0) }
AnimatedVisibility(
modifier = modifier,
visible = isRecording,
enter = fadeIn() + slideInVertically(),
exit = fadeOut() + slideOutVertically(),
) {
val currentTimer = if (isRecording) timer else lastTimer
Row(
modifier = Modifier
.fillMaxWidth()
.offset(x = (-4).dp),
horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterHorizontally),
verticalAlignment = Alignment.CenterVertically
) {
Box(
Modifier
.background(Color.Red, CircleShape)
.size(8.dp)
)
Text(
text = "${currentTimer.minutes}:${currentTimer.seconds}",
color = Color.White,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
}
}
LaunchedEffect(isRecording) {
while (isRecording) {
delay(1_000)
timer++
}
lastTimer = timer
timer = 0
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/VideoBox.kt | 1360658826 |
package com.ujizin.sample.feature.camera.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.ujizin.sample.R
@Composable
fun ConfigurationBox(
modifier: Modifier = Modifier,
onConfigurationClick: () -> Unit,
) {
Box(modifier) {
Button(
modifier = Modifier.clip(CircleShape),
contentPaddingValues = PaddingValues(16.dp),
onClick = onConfigurationClick,
) {
Image(
painter = painterResource(id = R.drawable.configuration),
contentDescription = stringResource(id = R.string.configuration)
)
}
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/ConfigurationSection.kt | 932077783 |
package com.ujizin.sample.feature.camera.components
import android.content.Intent
import android.net.Uri
import android.webkit.URLUtil
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.ujizin.sample.CamposerTheme
import kotlinx.coroutines.delay
@Composable
fun QrCodeBox(modifier: Modifier = Modifier, qrCodeText: String?) {
var latestQrCode by remember(Unit) { mutableStateOf(qrCodeText.orEmpty()) }
var showQrCode by remember { mutableStateOf(false) }
if (showQrCode) {
val context = LocalContext.current
val intent = remember(latestQrCode) {
Intent(Intent.ACTION_VIEW, Uri.parse(latestQrCode)).takeIf {
URLUtil.isValidUrl(latestQrCode)
}
}
Box(
modifier = modifier,
contentAlignment = Alignment.Center,
) {
Text(
modifier = Modifier
.clickable(enabled = intent != null) { context.startActivity(intent) }
.width(240.dp)
.background(Color.White, RoundedCornerShape(4.dp))
.padding(8.dp),
textAlign = TextAlign.Center,
text = latestQrCode,
fontWeight = FontWeight.SemiBold,
color = if (intent != null) Color(0xFF6891E4) else Color.Black,
overflow = TextOverflow.Ellipsis,
maxLines = 1,
)
}
}
LaunchedEffect(qrCodeText) {
if (qrCodeText != null) {
showQrCode = true
latestQrCode = qrCodeText
} else {
delay(1000)
showQrCode = false
}
}
}
@Preview
@Composable
private fun PreviewQrCodeBox() {
CamposerTheme {
QrCodeBox(qrCodeText = "#UJI")
}
}
@Preview
@Composable
private fun PreviewFullQrCodeBox() {
CamposerTheme {
QrCodeBox(qrCodeText = "https://www.google.com")
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/QrCodeBox.kt | 3470273665 |
package com.ujizin.sample.feature.camera.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.ujizin.sample.feature.camera.model.CameraOption
import java.io.File
@Composable
fun ActionBox(
modifier: Modifier = Modifier,
cameraOption: CameraOption,
isRecording: Boolean,
qrCodeText: String?,
lastPicture: File?,
isVideoSupported: Boolean,
onGalleryClick: () -> Unit,
onTakePicture: () -> Unit,
onSwitchCamera: () -> Unit,
onRecording: () -> Unit,
onCameraOptionChanged: (CameraOption) -> Unit,
) {
Column(
modifier = modifier,
) {
QrCodeBox(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
qrCodeText = qrCodeText)
OptionSection(
modifier = Modifier.fillMaxWidth(),
isVideoSupported = isVideoSupported,
currentCameraOption = cameraOption,
onCameraOptionChanged = onCameraOptionChanged
)
PictureActions(
modifier = Modifier
.fillMaxWidth()
.padding(top = 24.dp, bottom = 32.dp),
isVideo = cameraOption == CameraOption.Video,
lastPicture = lastPicture,
isRecording = isRecording,
onGalleryClick = onGalleryClick,
onRecording = onRecording,
onTakePicture = onTakePicture,
onSwitchCamera = onSwitchCamera
)
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/ActionsBox.kt | 1776706872 |
package com.ujizin.sample.feature.camera.components
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.unit.dp
@Composable
fun Button(
modifier: Modifier = Modifier,
enabled: Boolean = true,
contentPaddingValues: PaddingValues = PaddingValues(0.dp),
onClick: () -> Unit,
content: @Composable BoxScope.() -> Unit = {},
) {
val interactionSource = remember { MutableInteractionSource() }
val pressed by interactionSource.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.9F else 1F)
Box(
modifier = Modifier
.scale(scale)
.then(modifier)
.clickable(
enabled = enabled,
indication = rememberRipple(bounded = true),
interactionSource = interactionSource,
onClick = onClick,
)
.padding(contentPaddingValues),
contentAlignment = Alignment.Center,
content = content
)
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/Button.kt | 298902290 |
package com.ujizin.sample.feature.camera.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.ujizin.sample.feature.camera.model.CameraOption
@Composable
fun OptionSection(
modifier: Modifier = Modifier,
currentCameraOption: CameraOption,
isVideoSupported: Boolean,
onCameraOptionChanged: (CameraOption) -> Unit,
) {
Row(
modifier = modifier,
horizontalArrangement = Arrangement.Center,
) {
CameraOption.values().forEach { option ->
if (!isVideoSupported && option == CameraOption.Video) return@forEach
Text(
modifier = Modifier
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = { onCameraOptionChanged(option) },
)
.padding(vertical = 4.dp)
.width(80.dp),
text = stringResource(id = option.titleRes).replaceFirstChar { it.uppercase() },
fontSize = 16.sp,
maxLines = 1,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
color = if (currentCameraOption == option) Color.Yellow else Color.White
)
}
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/OptionSection.kt | 2297762741 |
package com.ujizin.sample.feature.camera.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import kotlinx.coroutines.delay
import java.io.File
@Composable
fun BlinkPictureBox(lastPicture: File?, isVideo: Boolean) {
var picture by remember(Unit) { mutableStateOf(lastPicture) }
if (!isVideo && lastPicture != picture) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
)
LaunchedEffect(lastPicture) {
delay(25)
picture = lastPicture
}
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/BlinkPictureBox.kt | 2619416379 |
package com.ujizin.sample.feature.camera.components
import androidx.compose.animation.*
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.ujizin.sample.extensions.roundTo
import com.ujizin.sample.feature.camera.model.Flash
import kotlinx.coroutines.delay
@Composable
fun SettingsBox(
modifier: Modifier = Modifier,
zoomRatio: Float,
zoomHasChanged: Boolean,
flashMode: Flash,
isRecording: Boolean,
isVideo: Boolean,
hasFlashUnit: Boolean,
onFlashModeChanged: (Flash) -> Unit,
onConfigurationClick: () -> Unit,
onZoomFinish: () -> Unit,
) {
Box(modifier = modifier) {
FlashBox(
modifier = Modifier.align(Alignment.TopStart),
hasFlashUnit = hasFlashUnit,
flashMode = flashMode,
isVideo = isVideo,
onFlashModeChanged = onFlashModeChanged
)
Column(
modifier = Modifier.align(Alignment.TopCenter),
horizontalAlignment = Alignment.CenterHorizontally,
) {
VideoBox(
modifier = Modifier.padding(top = 16.dp),
isRecording = isRecording,
)
AnimatedVisibility(
modifier = Modifier.padding(top = 16.dp),
enter = fadeIn() + slideInVertically(),
exit = fadeOut() + slideOutVertically(),
visible = zoomHasChanged
) {
Text(
text = "${zoomRatio.roundTo(1)}X",
fontSize = 24.sp,
textAlign = TextAlign.Center,
color = Color.White,
)
}
}
ConfigurationBox(
modifier = Modifier.align(Alignment.TopEnd),
onConfigurationClick = onConfigurationClick
)
}
LaunchedEffect(zoomRatio, zoomHasChanged) {
delay(1_000)
onZoomFinish()
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/SettingsBox.kt | 1365214206 |
package com.ujizin.sample.feature.camera.components
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.ujizin.sample.R
import coil.compose.AsyncImage
import coil.decode.VideoFrameDecoder
import coil.request.ImageRequest
import coil.request.videoFrameMillis
import kotlinx.coroutines.delay
import java.io.File
@Composable
fun PictureActions(
modifier: Modifier = Modifier,
isVideo: Boolean,
isRecording: Boolean,
lastPicture: File?,
onGalleryClick: () -> Unit,
onRecording: () -> Unit,
onTakePicture: () -> Unit,
onSwitchCamera: () -> Unit,
) {
Row(
modifier = modifier,
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically
) {
GalleryButton(lastPicture, onClick = onGalleryClick)
PictureButton(
isVideo = isVideo,
isRecording = isRecording,
onClick = { if (isVideo) onRecording() else onTakePicture() }
)
SwitchButton(onClick = onSwitchCamera)
}
}
@Composable
fun GalleryButton(lastPicture: File?, onClick: () -> Unit) {
var shouldAnimate by remember { mutableStateOf(false) }
val animScale by animateFloatAsState(targetValue = if (shouldAnimate) 1.25F else 1F)
AsyncImage(
modifier = Modifier
.scale(animScale)
.size(48.dp)
.clip(CircleShape)
.background(Color.Black.copy(alpha = 0.5F), CircleShape)
.clickable(onClick = onClick),
contentScale = ContentScale.Crop,
model = ImageRequest.Builder(LocalContext.current)
.data(lastPicture)
.decoderFactory(VideoFrameDecoder.Factory())
.videoFrameMillis(1)
.build(),
contentDescription = stringResource(R.string.gallery)
)
LaunchedEffect(lastPicture) {
shouldAnimate = true
delay(50)
shouldAnimate = false
}
}
@Composable
private fun SwitchButton(
modifier: Modifier = Modifier,
onClick: () -> Unit,
) {
var clicked by remember { mutableStateOf(false) }
val rotate by animateFloatAsState(
targetValue = if (clicked) 360F else 1F,
animationSpec = tween(durationMillis = 500)
)
Button(
modifier = Modifier
.rotate(rotate)
.size(48.dp)
.background(Color.DarkGray.copy(alpha = 0.25F), CircleShape)
.clip(CircleShape)
.then(modifier),
onClick = {
clicked = !clicked
onClick()
}
) {
Image(
modifier = Modifier.size(24.dp),
painter = painterResource(id = R.drawable.refresh),
colorFilter = ColorFilter.tint(Color.White),
contentDescription = stringResource(R.string.refresh)
)
}
}
@Composable
private fun PictureButton(
modifier: Modifier = Modifier,
isVideo: Boolean,
isRecording: Boolean,
onClick: () -> Unit,
) {
val color by animateColorAsState(
targetValue = if (isVideo) Color.Red else Color.Transparent,
animationSpec = tween(durationMillis = 250)
)
val innerPadding by animateDpAsState(targetValue = if (isRecording) 24.dp else 8.dp)
val percentShape by animateIntAsState(targetValue = if (isRecording) 25 else 50)
Button(
modifier = Modifier
.size(80.dp)
.border(BorderStroke(4.dp, Color.White), CircleShape)
.padding(innerPadding)
.background(color, RoundedCornerShape(percentShape))
.clip(CircleShape)
.then(modifier),
onClick = onClick
)
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/PictureActions.kt | 1636344595 |
package com.ujizin.sample.feature.camera.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.ujizin.sample.feature.camera.model.Flash
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun FlashBox(
modifier: Modifier = Modifier,
hasFlashUnit: Boolean,
isVideo: Boolean,
flashMode: Flash,
onFlashModeChanged: (Flash) -> Unit
) {
var expanded by remember { mutableStateOf(false) }
val isVisible by remember(hasFlashUnit) { derivedStateOf { hasFlashUnit && expanded }}
LazyColumn(modifier) {
itemsIndexed(Flash.getCurrentValues(isVideo), key = { _, it -> it.name }) { index, flash ->
AnimatedVisibility(
visible = isVisible,
enter = if (index == 0) EnterTransition.None else fadeIn() + slideInVertically(),
exit = fadeOut() + if (index == 0) ExitTransition.None else slideOutVertically()
) {
FlashButton(
modifier = Modifier
.padding(bottom = 8.dp)
.animateItemPlacement(),
tintColor = if (flashMode == flash) Color.Yellow else Color.White,
flash = flash
) {
expanded = false
onFlashModeChanged(flash)
}
}
}
}
if (!isVisible) {
FlashButton(enabled = hasFlashUnit, flash = flashMode) { expanded = true }
}
LaunchedEffect(isVideo) {
val hasOption = Flash.getCurrentValues(isVideo).any { it == flashMode }
if (!hasOption) onFlashModeChanged(Flash.Off)
}
}
@Composable
private fun FlashButton(
modifier: Modifier = Modifier,
flash: Flash,
tintColor: Color = Color.White,
enabled: Boolean = true,
onClick: () -> Unit,
) {
Button(
modifier = modifier.then(Modifier.clip(CircleShape)),
enabled = enabled,
contentPaddingValues = PaddingValues(16.dp),
onClick = onClick,
) {
Image(
modifier = Modifier.size(32.dp),
painter = painterResource(flash.drawableRes),
colorFilter = ColorFilter.tint(if (enabled) tintColor else Color.Gray),
contentDescription = stringResource(flash.contentRes)
)
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/components/FlashSection.kt | 2849817217 |
package com.ujizin.sample.feature.camera.model
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.ujizin.sample.R
enum class Flash(
@DrawableRes val drawableRes: Int,
@StringRes val contentRes: Int
) {
Off(R.drawable.flash_off, R.string.flash_off),
On(R.drawable.flash_on, R.string.flash_on),
Auto(R.drawable.flash_auto, R.string.flash_auto),
Always(R.drawable.flash_always, R.string.flash_always);
companion object {
fun getCurrentValues(isVideo: Boolean) = when {
isVideo -> listOf(Off, Always)
else -> values().toList()
}
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/model/Flash.kt | 448931015 |
package com.ujizin.sample.feature.camera.model
import android.os.Build
import androidx.annotation.StringRes
import com.ujizin.camposer.state.CaptureMode
import com.ujizin.sample.R
enum class CameraOption(@StringRes val titleRes: Int) {
Photo(R.string.photo),
Video(R.string.video),
QRCode(R.string.qr_code);
fun toCaptureMode(): CaptureMode = when(this) {
QRCode, Photo -> CaptureMode.Image
Video -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
CaptureMode.Video
} else {
throw IllegalStateException("Camera state not support video capture mode")
}
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/model/CameraOption.kt | 3504225796 |
package com.ujizin.sample.feature.camera
import android.graphics.ImageFormat.YUV_420_888
import android.graphics.ImageFormat.YUV_422_888
import android.graphics.ImageFormat.YUV_444_888
import android.os.Build
import android.util.Log
import androidx.camera.core.ImageProxy
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.zxing.BarcodeFormat
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.ujizin.camposer.state.CameraState
import com.ujizin.camposer.state.ImageCaptureResult
import com.ujizin.camposer.state.VideoCaptureResult
import com.ujizin.sample.data.local.datasource.FileDataSource
import com.ujizin.sample.data.local.datasource.UserDataSource
import com.ujizin.sample.domain.User
import com.ujizin.sample.extensions.getQRCodeResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.io.File
class CameraViewModel(
private val fileDataSource: FileDataSource,
private val userDataSource: UserDataSource,
) : ViewModel() {
private val _uiState: MutableStateFlow<CameraUiState> = MutableStateFlow(CameraUiState.Initial)
val uiState: StateFlow<CameraUiState> get() = _uiState
private val reader = MultiFormatReader().apply {
val map = mapOf(DecodeHintType.POSSIBLE_FORMATS to arrayListOf(BarcodeFormat.QR_CODE))
setHints(map)
}
private lateinit var user: User
init {
initCamera()
}
private fun initCamera() {
viewModelScope.launch {
userDataSource.getUser()
.onStart { CameraUiState.Initial }
.collect { user ->
_uiState.value = CameraUiState.Ready(user, fileDataSource.lastPicture).apply {
[email protected] = user
}
}
}
}
fun takePicture(cameraState: CameraState) = with(cameraState) {
viewModelScope.launch {
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> takePicture(
fileDataSource.imageContentValues,
onResult = ::onImageResult
)
else -> takePicture(
fileDataSource.getFile("jpg"),
::onImageResult
)
}
}
}
fun toggleRecording(cameraState: CameraState) = with(cameraState) {
viewModelScope.launch {
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> toggleRecording(
fileDataSource.videoContentValues,
onResult = ::onVideoResult
)
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
toggleRecording(
fileDataSource.getFile("mp4"),
onResult = ::onVideoResult
)
}
}
}
}
fun analyzeImage(image: ImageProxy) {
viewModelScope.launch {
if (image.format !in listOf(YUV_420_888, YUV_422_888, YUV_444_888)) {
Log.e("QRCodeAnalyzer", "Expected YUV, now = ${image.format}")
}
val qrCodeResult = reader.getQRCodeResult(image)
_uiState.update {
CameraUiState.Ready(
user = user,
lastPicture = fileDataSource.lastPicture,
qrCodeText = qrCodeResult?.text
)
}
image.close()
}
}
private fun captureSuccess() {
viewModelScope.launch {
_uiState.update {
CameraUiState.Ready(user = user, lastPicture = fileDataSource.lastPicture)
}
}
}
private fun onVideoResult(videoResult: VideoCaptureResult) {
when (videoResult) {
is VideoCaptureResult.Error -> onError(videoResult.throwable)
is VideoCaptureResult.Success -> captureSuccess()
}
}
private fun onImageResult(imageResult: ImageCaptureResult) {
when (imageResult) {
is ImageCaptureResult.Error -> onError(imageResult.throwable)
is ImageCaptureResult.Success -> captureSuccess()
}
}
private fun onError(throwable: Throwable?) {
_uiState.update { CameraUiState.Ready(user, fileDataSource.lastPicture, throwable) }
}
}
sealed interface CameraUiState {
object Initial : CameraUiState
data class Ready(
val user: User,
val lastPicture: File?,
val throwable: Throwable? = null,
val qrCodeText: String? = null,
) : CameraUiState
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/camera/CameraViewModel.kt | 945100271 |
package com.ujizin.sample.feature.gallery
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ujizin.sample.R
import com.ujizin.sample.components.Section
import com.ujizin.sample.extensions.getDuration
import com.ujizin.sample.extensions.minutes
import com.ujizin.sample.extensions.seconds
import coil.compose.AsyncImage
import coil.compose.AsyncImagePainter
import coil.decode.VideoFrameDecoder
import coil.request.ImageRequest
import coil.request.videoFramePercent
import org.koin.androidx.compose.get
import java.io.File
@Composable
fun GalleryScreen(
viewModel: GalleryViewModel = get(),
onBackPressed: () -> Unit,
onPreviewClick: (String) -> Unit,
) {
Section(
title = {
Text(stringResource(id = R.string.gallery).replaceFirstChar { it.uppercase() })
},
onBackPressed = onBackPressed
) {
Box(Modifier.padding(it)) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
when (val result: GalleryUiState = uiState) {
GalleryUiState.Initial -> GalleryLoading()
GalleryUiState.Empty -> GalleryEmpty()
is GalleryUiState.Success -> GallerySection(
imageFiles = result.images,
onPreviewClick = onPreviewClick,
)
}
}
}
}
@Composable
private fun GalleryEmpty() {
Box(
Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
modifier = Modifier.padding(24.dp),
textAlign = TextAlign.Center,
text = stringResource(id = R.string.gallery_empty_description).replaceFirstChar { it.uppercase() },
fontSize = 18.sp,
color = Color.Gray,
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun GallerySection(imageFiles: List<File>, onPreviewClick: (String) -> Unit) {
LazyVerticalGrid(
modifier = Modifier.fillMaxSize(),
columns = GridCells.Fixed(3),
horizontalArrangement = Arrangement.spacedBy(1.dp),
verticalArrangement = Arrangement.spacedBy(1.dp)
) {
items(imageFiles, { it.name }) { image ->
val context = LocalContext.current
var duration by rememberSaveable { mutableStateOf<Int?>(null) }
LaunchedEffect(Unit) { duration = image.getDuration(context) }
PlaceholderImage(
modifier = Modifier
.fillMaxSize()
.animateItemPlacement()
.aspectRatio(1F)
.clickable(onClick = { onPreviewClick(image.path) }),
data = image,
contentDescription = image.name,
placeholder = {
Box(
Modifier
.fillMaxSize()
.background(Color.LightGray)
)
},
) {
duration?.let { duration ->
Box(
modifier = Modifier.background(Color.Black.copy(0.25F)),
contentAlignment = Alignment.TopEnd
) {
Row(
modifier = Modifier.padding(4.dp),
horizontalArrangement = Arrangement.spacedBy(2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"${duration.minutes}:${duration.seconds}",
color = Color.White,
fontWeight = FontWeight.Bold,
fontSize = 12.sp,
)
Icon(
modifier = Modifier
.size(12.dp)
.background(Color.White, CircleShape),
imageVector = Icons.Rounded.PlayArrow,
tint = Color.Black,
contentDescription = stringResource(id = R.string.play),
)
}
}
}
}
}
}
}
@Composable
private fun PlaceholderImage(
modifier: Modifier = Modifier,
data: Any,
placeholder: @Composable () -> Unit,
contentDescription: String?,
innerContent: @Composable () -> Unit,
) {
var imageState: AsyncImagePainter.State by remember { mutableStateOf(AsyncImagePainter.State.Empty) }
Box(modifier) {
AsyncImage(
modifier = Modifier.fillMaxSize(),
model = ImageRequest.Builder(LocalContext.current)
.data(data)
.decoderFactory(VideoFrameDecoder.Factory())
.videoFramePercent(0.5)
.build(),
onState = { imageState = it },
contentScale = ContentScale.Crop,
contentDescription = contentDescription,
)
GalleryAnimationVisibility(
modifier = Modifier.fillMaxSize(),
visible = when (imageState) {
is AsyncImagePainter.State.Empty,
is AsyncImagePainter.State.Success,
-> false
is AsyncImagePainter.State.Loading,
is AsyncImagePainter.State.Error,
-> true
}
) { placeholder() }
GalleryAnimationVisibility(
modifier = Modifier.fillMaxSize(),
visible = when (imageState) {
is AsyncImagePainter.State.Empty,
is AsyncImagePainter.State.Loading,
is AsyncImagePainter.State.Error,
-> false
is AsyncImagePainter.State.Success -> true
}
) { innerContent() }
}
}
@Composable
private fun GalleryAnimationVisibility(
modifier: Modifier = Modifier,
visible: Boolean,
content: @Composable () -> Unit,
) {
AnimatedVisibility(
modifier = modifier,
enter = fadeIn(),
exit = fadeOut(),
visible = visible
) { content() }
}
@Composable
private fun GalleryLoading() {
Box(Modifier.fillMaxSize()) {
CircularProgressIndicator()
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/gallery/GalleryScreen.kt | 3005113696 |
package com.ujizin.sample.feature.gallery
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ujizin.sample.data.local.datasource.FileDataSource
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import java.io.File
class GalleryViewModel(fileDataSource: FileDataSource) : ViewModel() {
private val _uiState = MutableStateFlow(
fileDataSource.externalFiles.orEmpty().run {
if (isEmpty()) GalleryUiState.Empty else GalleryUiState.Success(this)
}
).stateIn(
viewModelScope,
started = SharingStarted.Eagerly,
initialValue = GalleryUiState.Initial
)
val uiState: StateFlow<GalleryUiState> get() = _uiState
}
sealed interface GalleryUiState {
object Initial : GalleryUiState
object Empty : GalleryUiState
data class Success(val images: List<File>) : GalleryUiState
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/gallery/GalleryViewModel.kt | 947814158 |
package com.ujizin.sample.feature.preview
import android.app.Activity
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.net.toUri
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ujizin.sample.R
import com.ujizin.sample.components.NavigationIcon
import com.ujizin.sample.extensions.observeAsState
import coil.compose.AsyncImage
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.ui.StyledPlayerView
import org.koin.androidx.compose.koinViewModel
import java.io.File
@Composable
fun PreviewScreen(
viewModel: PreviewViewModel = koinViewModel(),
onBackPressed: () -> Unit,
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val intentSenderLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartIntentSenderForResult()
) {
if (it.resultCode == Activity.RESULT_OK) {
onBackPressed()
}
Log.d("INTENT SENDER", "RESULT: ${it.resultCode}")
}
Log.d("PREVIEW SCREEN", "OPA")
when (val result: PreviewUiState = uiState) {
PreviewUiState.Initial -> {}
PreviewUiState.Empty -> {}
is PreviewUiState.Ready -> {
val context = LocalContext.current
when {
result.isVideo -> PreviewVideoSection(result.file)
else -> PreviewImageSection(result.file)
}
PreviewTopAppBar(
onBackPressed = onBackPressed,
onDeleteClick = {
viewModel.deleteFile(context, intentSenderLauncher, result.file)
}
)
}
PreviewUiState.Deleted -> LaunchedEffect(Unit) {
onBackPressed()
}
}
}
@Composable
fun PreviewTopAppBar(
onBackPressed: () -> Unit,
onDeleteClick: () -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
) {
NavigationIcon(
modifier = Modifier
.background(Color.Black.copy(alpha = 0.1F), CircleShape),
icon = Icons.Filled.ArrowBack,
contentDescription = stringResource(R.string.back),
onClick = onBackPressed
)
NavigationIcon(
modifier = Modifier
.background(Color.Black.copy(alpha = 0.1F), CircleShape),
icon = Icons.Filled.Delete,
contentDescription = stringResource(R.string.delete),
onClick = onDeleteClick
)
}
}
@Composable
private fun PreviewVideoSection(file: File) {
val context = LocalContext.current
val lifecycle by LocalLifecycleOwner.current.lifecycle.observeAsState()
val player = remember {
ExoPlayer.Builder(context).build().apply {
addMediaItem(MediaItem.fromUri(file.toUri()))
prepare()
playWhenReady = true
}
}
DisposableEffect(AndroidView(
modifier = Modifier
.fillMaxSize()
.background(Color.Black),
factory = { ctx ->
StyledPlayerView(ctx).apply { this.player = player }
},
update = { playerView ->
when (lifecycle) {
Lifecycle.Event.ON_PAUSE -> {
playerView.onPause()
player.pause()
}
Lifecycle.Event.ON_RESUME -> playerView.onResume()
else -> Unit
}
}
)) { onDispose { player.release() } }
}
@Composable
private fun PreviewImageSection(file: File) {
AsyncImage(
modifier = Modifier.fillMaxSize(),
model = file,
contentScale = ContentScale.Fit,
contentDescription = file.name,
)
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/preview/PreviewScreen.kt | 3285222937 |
package com.ujizin.sample.feature.preview
import android.content.Context
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ujizin.sample.extensions.delete
import com.ujizin.sample.extensions.isVideo
import com.ujizin.sample.router.Args
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import java.io.File
class PreviewViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
private val _uiState = MutableStateFlow<PreviewUiState>(PreviewUiState.Initial)
val uiState: StateFlow<PreviewUiState> = _uiState
init {
viewModelScope.launch {
flow {
val path =
savedStateHandle.get<String?>(Args.Path) ?: return@flow emit(PreviewUiState.Empty)
val file = File(Uri.decode(path))
emit(PreviewUiState.Ready(file, file.isVideo))
}.collect { state ->
_uiState.value = state
}
}
}
fun deleteFile(
context: Context,
intentSenderLauncher: ActivityResultLauncher<IntentSenderRequest>,
file: File
) {
viewModelScope.launch {
file.delete(context.contentResolver, intentSenderLauncher)
if (!file.exists()) {
_uiState.value = PreviewUiState.Deleted
}
}
}
}
sealed interface PreviewUiState {
object Initial : PreviewUiState
object Empty : PreviewUiState
object Deleted : PreviewUiState
data class Ready(val file: File, val isVideo: Boolean) : PreviewUiState
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/preview/PreviewViewModel.kt | 1888251857 |
package com.ujizin.sample.feature.permission
import android.os.Build
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.ujizin.sample.R
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun AppPermission(content: @Composable () -> Unit) {
val permissionsState = rememberMultiplePermissionsState(
mutableListOf(
android.Manifest.permission.CAMERA,
android.Manifest.permission.RECORD_AUDIO,
).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
add(android.Manifest.permission.POST_NOTIFICATIONS)
add(android.Manifest.permission.READ_MEDIA_AUDIO)
add(android.Manifest.permission.READ_MEDIA_VIDEO)
add(android.Manifest.permission.READ_MEDIA_IMAGES)
} else {
add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
}
)
if (permissionsState.allPermissionsGranted) {
content()
} else {
DeniedSection {
permissionsState.launchMultiplePermissionRequest()
}
}
LaunchedEffect(Unit) {
permissionsState.launchMultiplePermissionRequest()
}
}
@Composable
private fun DeniedSection(onClick: () -> Unit) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
modifier = Modifier.padding(16.dp),
text = stringResource(
id = R.string.request_allow_permissions,
stringResource(id = R.string.app_name),
).replaceFirstChar { it.uppercase() },
fontSize = 20.sp,
textAlign = TextAlign.Center
)
Button(
modifier = Modifier.width(120.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Gray),
contentPadding = PaddingValues(vertical = 12.dp, horizontal = 8.dp),
onClick = onClick
) {
Text(stringResource(android.R.string.ok), color = Color.White)
}
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/feature/permission/AppPermission.kt | 1176738477 |
package com.ujizin.sample.data.mapper
import com.ujizin.sample.domain.User
import com.ujizin.sample.data.local.User as LocalUser
class UserMapper {
fun toDomain(user: LocalUser) = with(user) {
User(
usePinchToZoom = usePinchToZoom,
useTapToFocus = useTapToFocus,
useCamFront = useCamFront
)
}
fun toLocal(user: User) = with(user) {
LocalUser(
usePinchToZoom = usePinchToZoom,
useTapToFocus = useTapToFocus,
useCamFront = useCamFront
)
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/data/mapper/UserMapper.kt | 329574885 |
package com.ujizin.sample.data.local.datasource
import com.ujizin.sample.data.local.UserStore
import com.ujizin.sample.data.mapper.UserMapper
import com.ujizin.sample.domain.User
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
class UserDataSource(
private val userStore: UserStore,
private val mapper: UserMapper,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO,
) {
fun getUser(): Flow<User> = userStore.getUser().map { mapper.toDomain(it) }.flowOn(dispatcher)
suspend fun updateUser(user: User) = withContext(dispatcher) {
userStore.updateUser(mapper.toLocal(user))
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/data/local/datasource/UserDataSource.kt | 1137151608 |
package com.ujizin.sample.data.local.datasource
import android.content.ContentValues
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import java.io.File
import java.util.UUID
class FileDataSource {
private val externalDir = "${Environment.DIRECTORY_DCIM}${File.separator}$RELATIVE_PATH"
private val currentFileName: String
get() = "${System.currentTimeMillis()}-${UUID.randomUUID()}"
private val externalStorage
get() = Environment.getExternalStoragePublicDirectory(externalDir).apply { mkdirs() }
val externalFiles
get() = externalStorage.listFiles()?.sortedByDescending { it.lastModified() }
val lastPicture get() = externalFiles?.firstOrNull()
fun getFile(
extension: String = "jpg",
): File = File(externalStorage.path, "$currentFileName.$extension").apply {
if (parentFile?.exists() == false) parentFile?.mkdirs()
createNewFile()
}
@RequiresApi(Build.VERSION_CODES.Q)
val imageContentValues: ContentValues = getContentValues(JPEG_MIME_TYPE)
@RequiresApi(Build.VERSION_CODES.Q)
val videoContentValues: ContentValues = getContentValues(VIDEO_MIME_TYPE)
@RequiresApi(Build.VERSION_CODES.Q)
private fun getContentValues(mimeType: String) = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, currentFileName)
put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
put(MediaStore.MediaColumns.RELATIVE_PATH, externalDir)
}
companion object {
private const val JPEG_MIME_TYPE = "image/jpeg"
private const val VIDEO_MIME_TYPE = "video/mp4"
private const val RELATIVE_PATH = "Camposer"
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/data/local/datasource/FileDataSource.kt | 1666073168 |
package com.ujizin.sample.data.local
import android.content.Context
import androidx.annotation.WorkerThread
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
interface UserStore {
fun getUser(): Flow<User>
suspend fun updateUser(user: User)
}
internal class UserStoreImpl(
context: Context,
private val serializer: Json,
) : UserStore {
private val dataStore: DataStore<Preferences>
private val userKey = stringPreferencesKey(USER_KEY)
init {
dataStore = context.dataStore
}
@WorkerThread
override fun getUser(): Flow<User> = dataStore.data.map { preferences ->
val user = preferences[userKey] ?: return@map User.Default
serializer.decodeFromString(user)
}
@WorkerThread
override suspend fun updateUser(user: User) {
dataStore.edit { preferences -> preferences[userKey] = serializer.encodeToString(user) }
}
companion object {
private const val USER_KEY = "user"
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/data/local/UserStore.kt | 2219172729 |
package com.ujizin.sample.data.local
import kotlinx.serialization.Serializable
@Serializable
data class User(
val usePinchToZoom: Boolean,
val useTapToFocus: Boolean,
val useCamFront: Boolean,
) {
companion object {
val Default = User(usePinchToZoom = true, useTapToFocus = true, useCamFront = false)
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/data/local/User.kt | 2603814658 |
package com.ujizin.sample.domain
import androidx.compose.runtime.Immutable
@Immutable
data class User(
val usePinchToZoom: Boolean,
val useTapToFocus: Boolean,
val useCamFront: Boolean,
)
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/domain/User.kt | 3896901065 |
package com.ujizin.sample
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Typography
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontFamily
@Composable
fun CamposerTheme(content: @Composable () -> Unit) {
MaterialTheme(
colors = MaterialTheme.colors.copy(
primary = colorResource(id = R.color.primary),
background = colorResource(id = R.color.light_gray),
),
typography = Typography(defaultFontFamily = FontFamily.SansSerif),
content = content
)
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/CamposerTheme.kt | 2808663817 |
package com.ujizin.sample.router
object Args {
const val Path = "path"
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/router/Args.kt | 3493582434 |
package com.ujizin.sample.router
import android.net.Uri
sealed class Router(val route: String) {
object Camera : Router("camera")
object Gallery : Router("gallery")
object Configuration : Router("configuration")
object Preview : Router("preview/{${Args.Path}}") {
fun createRoute(path: String) = "preview/${Uri.encode(path)}"
}
}
| camerajetpackcompose/sample/src/main/java/com/ujizin/sample/router/Router.kt | 103247877 |
package com.ujizin.sample.router
import androidx.compose.runtime.Composable
import androidx.navigation.NamedNavArgument
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDeepLink
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
fun NavGraphBuilder.route(
route: Router,
arguments: List<NamedNavArgument> = emptyList(),
deepLinks: List<NavDeepLink> = emptyList(),
content: @Composable (NavBackStackEntry) -> Unit
) {
composable(route.route, arguments, deepLinks, content)
}
fun NavHostController.navigate(route: Router) {
navigate(route.route) {
popUpTo(route.route) {
inclusive = true
}
}
} | camerajetpackcompose/sample/src/main/java/com/ujizin/sample/router/RouterExtensions.kt | 1467153165 |
package com.ujizin.camposer
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.ujizin.camposer.state.CamSelector
import com.ujizin.camposer.state.FlashMode
import com.ujizin.camposer.state.rememberFlashMode
import junit.framework.TestCase.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
internal class FlashModeTest : CameraTest() {
private lateinit var flashMode: MutableState<FlashMode>
@Test
fun test_flashModes() = with(composeTestRule) {
initFlashCamera(camSelector = CamSelector.Back)
if (!cameraState.hasFlashUnit) return
FlashMode.values().forEach { mode ->
flashMode.value = mode
onNodeWithTag("${flashMode.value}").assertIsDisplayed()
runOnIdle { assertEquals(mode, cameraState.flashMode) }
}
}
@Test
fun test_flashModeWithNoUnit() = with(composeTestRule) {
initFlashCamera(camSelector = CamSelector.Front)
// Ensure that there's no flash unit on device
cameraState.hasFlashUnit = false
flashMode.value = FlashMode.On
onNodeWithTag("${FlashMode.On}").assertDoesNotExist()
runOnIdle { assertEquals(FlashMode.Off, cameraState.flashMode) }
}
private fun ComposeContentTestRule.initFlashCamera(
camSelector: CamSelector
) = initCameraState { state ->
flashMode = state.rememberFlashMode(FlashMode.Off)
CameraPreview(
Modifier.testTag("${flashMode.value}"),
cameraState = state,
flashMode = flashMode.value,
camSelector = camSelector,
)
}
}
| camerajetpackcompose/camposer/src/androidTest/java/com/ujizin/camposer/FlashModeTest.kt | 1270122604 |
package com.ujizin.camposer
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import junit.framework.TestCase.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
internal class ExposureCompensationTest: CameraTest() {
private lateinit var exposureCompensation: MutableState<Int>
private val currentExposure: Int?
get() = cameraState.controller.cameraInfo?.exposureState?.exposureCompensationIndex
@Test
fun test_minExposureCompensation() = with(composeTestRule) {
initCameraWithExposure(0)
exposureCompensation.value = cameraState.minExposure
runOnIdle {
assertEquals(cameraState.minExposure, currentExposure)
assertEquals(exposureCompensation.value, currentExposure)
}
}
@Test
fun test_maxExposureCompensation() = with(composeTestRule) {
initCameraWithExposure(0)
exposureCompensation.value = cameraState.maxExposure
runOnIdle {
assertEquals(cameraState.maxExposure, currentExposure)
assertEquals(exposureCompensation.value, currentExposure)
}
}
@Test
fun test_invalidExposureCompensation() = with(composeTestRule) {
initCameraWithExposure(0)
exposureCompensation.value = Int.MAX_VALUE
runOnIdle {
assertNotEquals(cameraState.maxExposure, currentExposure)
assertNotEquals(exposureCompensation.value, currentExposure)
assertEquals(cameraState.initialExposure, currentExposure)
}
}
private fun ComposeContentTestRule.initCameraWithExposure(
exposure: Int,
) = initCameraState { state ->
exposureCompensation = remember { mutableStateOf(exposure) }
CameraPreview(
cameraState = state,
exposureCompensation = exposureCompensation.value
)
}
} | camerajetpackcompose/camposer/src/androidTest/java/com/ujizin/camposer/ExposureCompensationTest.kt | 4263987851 |
package com.ujizin.camposer
import android.content.Context
import android.net.Uri
import android.os.Build
import androidx.camera.core.ImageProxy
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import com.ujizin.camposer.state.CaptureMode
import com.ujizin.camposer.state.ImageCaptureResult
import com.ujizin.camposer.state.VideoCaptureResult
import com.ujizin.camposer.state.rememberImageAnalyzer
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
@RunWith(AndroidJUnit4::class)
@LargeTest
internal class CaptureModeTest : CameraTest() {
private val context: Context
get() = InstrumentationRegistry.getInstrumentation().context
@Test
@Ignore("Flaky test, sometimes throw exception \"Camera closed\"")
fun test_captureMode() = with(composeTestRule) {
initCaptureModeCamera(CaptureMode.Image)
runOnIdle {
val imageFile = File(context.filesDir, IMAGE_TEST_FILENAME).apply { createNewFile() }
cameraState.takePicture(imageFile) { result ->
when (result) {
is ImageCaptureResult.Error -> throw result.throwable
is ImageCaptureResult.Success -> {
assertEquals(Uri.fromFile(imageFile), result.savedUri)
assertEquals(CaptureMode.Image, cameraState.captureMode)
}
}
}
}
}
@Test
fun test_videoCaptureMode() = with(composeTestRule) {
// No support for API Level 23 below
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
initCaptureModeCamera(CaptureMode.Video)
runOnIdle {
val videoFile = File(context.filesDir, VIDEO_TEST_FILENAME).apply { createNewFile() }
cameraState.startRecording(videoFile) { result ->
when (result) {
is VideoCaptureResult.Error -> {
throw result.throwable ?: Exception(result.message)
}
is VideoCaptureResult.Success -> {
assertEquals(Uri.fromFile(videoFile), result.savedUri)
assertEquals(CaptureMode.Video, cameraState.captureMode)
}
}
}
runBlocking {
delay(RECORD_VIDEO_DELAY)
cameraState.stopRecording()
}
}
}
@Test
fun test_videoCaptureModeWithAnalysis() = with(composeTestRule) {
// No support for API Level 23 below
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
var isAnalyzeCalled = false
initCaptureModeCamera(CaptureMode.Video) {
isAnalyzeCalled = true
}
if (!cameraState.isImageAnalysisSupported) return
runOnIdle {
val videoFile = File(context.filesDir, VIDEO_TEST_FILENAME).apply { createNewFile() }
cameraState.startRecording(videoFile) { result ->
when (result) {
is VideoCaptureResult.Error -> {
throw result.throwable ?: Exception(result.message)
}
is VideoCaptureResult.Success -> {
assertEquals(Uri.fromFile(videoFile), result.savedUri)
assertEquals(CaptureMode.Video, cameraState.captureMode)
if (cameraState.isImageAnalysisSupported) {
assertEquals(true, cameraState.isImageAnalysisEnabled)
assertEquals(true, isAnalyzeCalled)
}
}
}
}
runBlocking {
delay(RECORD_VIDEO_DELAY)
cameraState.stopRecording()
}
}
}
private fun ComposeContentTestRule.initCaptureModeCamera(
captureMode: CaptureMode,
analyzer: ((ImageProxy) -> Unit)? = null,
) = initCameraState { state ->
CameraPreview(
cameraState = state,
captureMode = captureMode,
imageAnalyzer = analyzer?.takeIf {
cameraState.isImageAnalysisSupported
}?.let { state.rememberImageAnalyzer(analyze = it) },
isImageAnalysisEnabled = cameraState.isImageAnalysisSupported && analyzer != null
)
}
private companion object {
private const val RECORD_VIDEO_DELAY = 2000L
private const val IMAGE_TEST_FILENAME = "capture_mode_test.jpg"
private const val VIDEO_TEST_FILENAME = "capture_mode_test.mp4"
}
}
| camerajetpackcompose/camposer/src/androidTest/java/com/ujizin/camposer/CaptureModeTest.kt | 4015170287 |
package com.ujizin.camposer
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.ujizin.camposer.state.ImageCaptureMode
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
internal class ImageCaptureModeTest : CameraTest() {
private lateinit var imageCaptureMode: MutableState<ImageCaptureMode>
@Test
fun test_imageCaptureMode() = with(composeTestRule) {
initImageCaptureModeCamera(ImageCaptureMode.MinLatency)
Assert.assertEquals(cameraState.imageCaptureMode, ImageCaptureMode.MinLatency)
imageCaptureMode.value = ImageCaptureMode.MaxQuality
runOnIdle {
Assert.assertEquals(
cameraState.imageCaptureMode,
ImageCaptureMode.MaxQuality
)
}
}
private fun ComposeContentTestRule.initImageCaptureModeCamera(
initialValue: ImageCaptureMode
) = initCameraState { state ->
imageCaptureMode = remember { mutableStateOf(initialValue) }
CameraPreview(
cameraState = state,
imageCaptureMode = imageCaptureMode.value,
)
}
} | camerajetpackcompose/camposer/src/androidTest/java/com/ujizin/camposer/ImageCaptureModeTest.kt | 4229608254 |
package com.ujizin.camposer
import androidx.camera.core.TorchState
import androidx.compose.runtime.MutableState
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ujizin.camposer.state.CameraState
import com.ujizin.camposer.state.rememberTorch
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
internal class TorchTest : CameraTest() {
private lateinit var torchState: MutableState<Boolean>
private val cameraXEnableTorch: Boolean
get() = cameraState.controller.torchState.value == TorchState.ON
/**
* AVD does not have torch and [CameraState.hasFlashUnit] it's not enough in this case
* */
private val isCameraXFlashSupported: Boolean
get() = with(cameraState.controller) {
val oldValue = torchState.value == TorchState.ON
enableTorch(true)
val isSupported = torchState.value == TorchState.ON
enableTorch(oldValue)
isSupported
}
@Test
fun test_toggleTorch() = with(composeTestRule) {
initTorchCamera()
runOnIdle {
assertEquals(false, cameraState.enableTorch)
assertEquals(false, cameraXEnableTorch)
}
torchState.value = true
runOnIdle {
if (isCameraXFlashSupported) {
assertEquals(true, cameraState.enableTorch)
assertEquals(true, cameraXEnableTorch)
}
}
}
private fun ComposeContentTestRule.initTorchCamera(
initialValue: Boolean = false
) = initCameraState { state ->
torchState = state.rememberTorch(initialValue)
CameraPreview(
cameraState = state,
enableTorch = torchState.value
)
}
} | camerajetpackcompose/camposer/src/androidTest/java/com/ujizin/camposer/TorchTest.kt | 3476312460 |
package com.ujizin.camposer
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ujizin.camposer.state.CamSelector
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
internal class CamSelectorTest : CameraTest() {
private lateinit var camSelectorState: MutableState<CamSelector>
private lateinit var isCamSwitchedToFront: MutableState<Boolean>
private lateinit var isCamSwitchedToBack: MutableState<Boolean>
private lateinit var isPreviewStreamChanged: MutableState<Boolean>
@Before
fun setup() {
isCamSwitchedToFront = mutableStateOf(false)
isCamSwitchedToBack = mutableStateOf(false)
isPreviewStreamChanged = mutableStateOf(false)
}
@Test
fun test_camSelectorToFront() = with(composeTestRule) {
initCamSelectorCamera(CamSelector.Back)
camSelectorState.value = CamSelector.Front
runOnIdle {
assertEquals(true, isCamSwitchedToFront.value)
assertEquals(true, isPreviewStreamChanged.value)
assertEquals(false, isCamSwitchedToBack.value)
}
}
@Test
fun test_camSelectorToBack() = with(composeTestRule) {
initCamSelectorCamera(CamSelector.Front)
camSelectorState.value = CamSelector.Back
runOnIdle {
assertEquals(true, isCamSwitchedToBack.value)
assertEquals(true, isPreviewStreamChanged.value)
assertEquals(false, isCamSwitchedToFront.value)
}
}
private fun ComposeContentTestRule.initCamSelectorCamera(
initialValue: CamSelector
) = initCameraState { state ->
camSelectorState = remember { mutableStateOf(initialValue) }
isCamSwitchedToBack = remember { mutableStateOf(false) }
isCamSwitchedToFront = remember { mutableStateOf(false) }
isPreviewStreamChanged = remember { mutableStateOf(false) }
CameraPreview(
cameraState = state,
camSelector = camSelectorState.value,
onSwitchToBack = {
LaunchedEffect(Unit) { isCamSwitchedToBack.value = true }
},
onSwitchToFront = {
LaunchedEffect(Unit) { isCamSwitchedToFront.value = true }
},
onPreviewStreamChanged = { isPreviewStreamChanged.value = true }
)
}
}
| camerajetpackcompose/camposer/src/androidTest/java/com/ujizin/camposer/CamSelectorTest.kt | 3293434182 |
package com.ujizin.camposer
import android.Manifest
import android.os.Build
import androidx.compose.runtime.Composable
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.rule.GrantPermissionRule
import com.ujizin.camposer.state.CameraState
import com.ujizin.camposer.state.rememberCameraState
import org.junit.Rule
internal abstract class CameraTest {
@get:Rule
val composeTestRule = createComposeRule()
@get:Rule
val permissions: GrantPermissionRule = GrantPermissionRule.grant(
*mutableListOf(
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
add(Manifest.permission.POST_NOTIFICATIONS)
add(Manifest.permission.READ_MEDIA_AUDIO)
add(Manifest.permission.READ_MEDIA_VIDEO)
add(Manifest.permission.READ_MEDIA_IMAGES)
} else {
add(Manifest.permission.READ_EXTERNAL_STORAGE)
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
}.toTypedArray()
)
protected lateinit var cameraState: CameraState
protected fun ComposeContentTestRule.initCameraState(
block: @Composable (CameraState) -> Unit
) {
setContent {
cameraState = rememberCameraState()
block(cameraState)
}
waitUntil(CAMERA_TIMEOUT) { cameraState.isStreaming }
}
private companion object {
private const val CAMERA_TIMEOUT = 2_500L
}
}
| camerajetpackcompose/camposer/src/androidTest/java/com/ujizin/camposer/CameraTest.kt | 4133989710 |
package com.ujizin.camposer
import android.util.Size
import androidx.camera.camera2.internal.compat.workaround.TargetAspectRatio.RATIO_16_9
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.ujizin.camposer.state.ImageTargetSize
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
internal class ImageCaptureTargetSizeTest : CameraTest() {
private lateinit var imageCaptureTargetSize: MutableState<ImageTargetSize>
@Test
fun test_imageCaptureTargetSize() = with(composeTestRule) {
initImageCaptureTargetSizeCamera(ImageTargetSize(RATIO_16_9))
runOnIdle {
assertEquals(
cameraState.imageCaptureTargetSize,
ImageTargetSize(RATIO_16_9)
)
}
imageCaptureTargetSize.value = ImageTargetSize(Size(1600, 1200))
runOnIdle {
assertEquals(
cameraState.imageCaptureTargetSize,
ImageTargetSize(Size(1600, 1200))
)
}
}
private fun ComposeContentTestRule.initImageCaptureTargetSizeCamera(
initialValue: ImageTargetSize
) = initCameraState { state ->
imageCaptureTargetSize = remember { mutableStateOf(initialValue) }
CameraPreview(
cameraState = state,
imageCaptureTargetSize = imageCaptureTargetSize.value,
)
}
}
| camerajetpackcompose/camposer/src/androidTest/java/com/ujizin/camposer/ImageCaptureTargetSizeTest.kt | 2141608410 |
package com.ujizin.camposer
import android.content.res.Configuration
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.test.pinch
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
internal class ZoomRatioTest : CameraTest() {
lateinit var zoomRatio: MutableState<Float>
private val currentCameraXZoom: Float?
get() = cameraState.controller.zoomState.value?.zoomRatio
private lateinit var configurationScreen: Configuration
private val Offset.Companion.middle
get() = with(configurationScreen) { Offset(screenWidthDp / 2F, screenHeightDp / 2F) }
private val Offset.Companion.end
get() = with(configurationScreen) {
Offset(screenWidthDp.toFloat(), screenHeightDp.toFloat())
}
@Test
fun test_limitToMaxZoomRatio() = with(composeTestRule) {
initZoomCamera(UNREACHABLE_MAX_ZOOM_VALUE)
runOnIdle {
assertNotEquals(UNREACHABLE_MAX_ZOOM_VALUE, currentCameraXZoom)
assertEquals(cameraState.maxZoom, currentCameraXZoom)
}
}
@Test
fun test_limitToMinZoomRatio() = with(composeTestRule) {
initZoomCamera(UNREACHABLE_MIN_ZOOM_VALUE)
runOnIdle {
assertNotEquals(UNREACHABLE_MIN_ZOOM_VALUE, currentCameraXZoom)
assertEquals(cameraState.minZoom, currentCameraXZoom)
}
}
@Test
fun test_zoomChangeValueToMax() = with(composeTestRule) {
initZoomCamera(DEFAULT_ZOOM_VALUE)
zoomRatio.value = cameraState.maxZoom
runOnIdle {
assertEquals(cameraState.maxZoom, zoomRatio.value)
assertEquals(currentCameraXZoom, zoomRatio.value)
}
}
@Test
fun test_pinchToZoom() = with(composeTestRule) {
initZoomCamera(DEFAULT_ZOOM_VALUE)
composeTestRule
.onNodeWithTag(CAMERA_ZOOM_TAG)
.performTouchInput {
pinch(Offset.middle, Offset.Zero, Offset.middle, Offset.end, 50L)
}
runOnIdle {
if (cameraState.isZoomSupported) {
assertNotEquals(DEFAULT_ZOOM_VALUE, zoomRatio.value)
}
assertEquals(currentCameraXZoom, zoomRatio.value)
}
}
@Test
fun test_pinchToZoomDisable() = with(composeTestRule) {
initZoomCamera(DEFAULT_ZOOM_VALUE, isPinchToZoomEnabled = false)
composeTestRule
.onNodeWithTag(CAMERA_ZOOM_TAG)
.performTouchInput {
pinch(Offset.middle, Offset.Zero, Offset.middle, Offset.end, 50L)
}
runOnIdle {
assertEquals(DEFAULT_ZOOM_VALUE, zoomRatio.value)
assertEquals(currentCameraXZoom, zoomRatio.value)
}
}
private fun ComposeContentTestRule.initZoomCamera(
initialValue: Float = DEFAULT_ZOOM_VALUE,
isPinchToZoomEnabled: Boolean = true,
) = initCameraState { state ->
configurationScreen = LocalConfiguration.current
zoomRatio = remember { mutableStateOf(initialValue) }
CameraPreview(
modifier = Modifier.testTag(CAMERA_ZOOM_TAG),
cameraState = state,
zoomRatio = zoomRatio.value,
onZoomRatioChanged = { zoomRatio.value = it },
isPinchToZoomEnabled = isPinchToZoomEnabled
)
}
companion object {
private const val CAMERA_ZOOM_TAG = "camera_zoom_tag"
private const val UNREACHABLE_MIN_ZOOM_VALUE = -1F
private const val UNREACHABLE_MAX_ZOOM_VALUE = 9999F
private const val DEFAULT_ZOOM_VALUE = 1F
}
}
| camerajetpackcompose/camposer/src/androidTest/java/com/ujizin/camposer/ZoomRatioTest.kt | 2635880112 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.