content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.coroutines.basics
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.coroutines.basics.test", appContext.packageName)
}
} | coroutine-ultimate-guild/basics/src/androidTest/java/com/coroutines/basics/ExampleInstrumentedTest.kt | 3305147041 |
package com.coroutines.basics
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | coroutine-ultimate-guild/basics/src/test/java/com/coroutines/basics/ExampleUnitTest.kt | 2139709810 |
package com.coroutines.basics.coroutineContext
import kotlin.coroutines.CoroutineContext
class CoroutineContextProviderImpl(
private val context: CoroutineContext,
) : CoroutineContextProvider {
override fun context(): CoroutineContext {
return context
}
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/coroutineContext/CoroutineContextProviderImpl.kt | 3800828522 |
package com.coroutines.basics.coroutineContext
import kotlin.coroutines.CoroutineContext
interface CoroutineContextProvider {
fun context(): CoroutineContext
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/coroutineContext/CoroutineContextProvider.kt | 190500094 |
package com.coroutines.basics.coroutineContext
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
fun main() {
val defaultDispatcher = Dispatchers.Default // 1- first element of coroutine context
val coroutineErrorHandler = CoroutineExceptionHandler { context, error ->
println("Problem with coroutine: $error")
} // 2- second element of coroutine context
val emptyParentJob = Job() // 3- third element of coroutine context
val combinedContext = defaultDispatcher + coroutineErrorHandler + emptyParentJob
GlobalScope.launch(context = combinedContext) {
println(Thread.currentThread().name)
}
Thread.sleep(50)
// context provider
val parentJob = Job()
val provider: CoroutineContextProvider =
CoroutineContextProviderImpl(context = parentJob + Dispatchers.IO)
GlobalScope.launch(context = provider.context()) {
println(Thread.currentThread().name)
}
Thread.sleep(50)
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/coroutineContext/CoroutineContext.kt | 1613379237 |
package com.coroutines.basics.contextSwitch
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.launch
import java.util.concurrent.Executors
fun main() {
GlobalScope.launch { // emptyCoroutineContext
println("This is a coroutine")
}
Thread.sleep(50)
GlobalScope.launch { // print the name of current thread aka DefaultDispatcher
println(Thread.currentThread().name)
}
Thread.sleep(50)
GlobalScope.launch(context = Dispatchers.Default) {
// printing the same as previous one
println(Thread.currentThread().name)
}
Thread.sleep(50)
GlobalScope.launch(context = Dispatchers.Unconfined) {
// which dispatcher is Unconfined running on?
println(Thread.currentThread().name)
}
Thread.sleep(50)
// creating a new work-stealing executor for executing a sample task :
val executorDispatcher = Executors.newWorkStealingPool().asCoroutineDispatcher()
GlobalScope.launch(context = executorDispatcher) {
println(Thread.currentThread().name)
}
Thread.sleep(50)
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/contextSwitch/ContextSwitch.kt | 1481746173 |
package com.coroutines.basics.suspensionConcept
import com.coroutines.basics.api.executeBackground
import com.coroutines.basics.api.executeMain
import com.coroutines.basics.api.getValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.concurrent.thread
fun main() {
getUserFromNetworkCallback("202") { user, error ->
user?.run(::println)
error?.printStackTrace()
}
println("main end")
/**
* suspending
*/
executeBackground {
val user = getUserStandard("101")
executeMain { println(user) }
}
Thread.sleep(1500)
executeBackground {
val user = getValue { getUserStandard("101") }
executeMain { println(user) }
}
/**\
* with context
*/
GlobalScope.launch(Dispatchers.Main) {
val user = getUserSuspended("101")
println(user)
}
}
private fun getUserStandard(userId: String): SuspendUser {
Thread.sleep(1000)
return SuspendUser(userId, "Filip")
}
private fun getUserFromNetworkCallback(
userId: String,
onUserResponse: (SuspendUser?, Throwable?) -> Unit,
) {
thread {
try {
Thread.sleep(1000)
val user = SuspendUser(userId, "Filip")
onUserResponse(user, null)
} catch (error: Throwable) {
onUserResponse(null, error)
}
}
println("end")
}
private suspend fun getUserSuspended(userId: String): SuspendUser = withContext(Dispatchers.Default) {
delay(1000)
SuspendUser(userId, "Filip")
}
internal data class SuspendUser(
val id: String,
val name: String,
)
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/suspensionConcept/SuspendVsNonSuspend.kt | 3765184954 |
package com.coroutines.basics.suspensionConcept
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
fun main() {
mainDispatcherFun()
}
fun coroutineBuilder() {
(1..10000).forEach {
GlobalScope.launch {
val threadName = Thread.currentThread().name
println("$it printed on thread $threadName")
}
Thread.sleep(1000)
}
}
fun delayFun() {
GlobalScope.launch {
println("Hello coroutine!")
delay(500)
println("Right back at ya!")
}
Thread.sleep(1000)
}
fun jobFun() {
val job1 = GlobalScope.launch(start = CoroutineStart.LAZY) {
delay(200)
println("Pong")
delay(200)
}
GlobalScope.launch {
delay(200)
println("Ping")
job1.join()
println("Ping")
delay(200)
}
Thread.sleep(1000)
}
fun jobHierarchy() {
with(GlobalScope) {
val parentJon = launch {
delay(200)
println("Im the parent")
delay(200)
}
launch(context = parentJon) {
delay(200)
println("Im a child")
delay(200)
}
if (parentJon.children.iterator().hasNext()) {
println("The job has children!")
} else {
println("th job has no children")
}
Thread.sleep(1000)
}
}
fun standardFunWithCoroutine() {
var isDoorOpen = false
println("Unlocking the door ... please wait.\n")
GlobalScope.launch {
delay(3000)
isDoorOpen = true
}
GlobalScope.launch {
repeat(4) {
println("Trying to open the door... \n")
delay(800)
if (isDoorOpen) {
println("Opened the door! \n")
} else {
println("The door is still locked \n")
}
}
}
Thread.sleep(5000)
}
fun mainDispatcherFun() {
GlobalScope.launch {
val bigThreadName = Thread.currentThread().name
println("Im Job 1 thread $bigThreadName")
delay(200)
GlobalScope.launch(Dispatchers.Main) {
val uiThreadName = Thread.currentThread().name
println("Im Job 2 in thread $uiThreadName")
}
}
Thread.sleep(1000)
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/suspensionConcept/MainHolder.kt | 2020834145 |
package com.coroutines.basics.asyncAwait
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.io.File
fun main() {
val userId = 992
val scope = CustomScope()
/**
*
* callback pattern
getUserByIdFromNetwork(userId) { user ->
println(user)
}
*/
/**
*
Async/Await pattern
GlobalScope.launch {
val userData = getUserByIdFromNetwork(userId)
println(userData.await())
}
Thread.sleep(5000)
*/
scope.launch {
println("Finding user")
val userDeferred = getUserByIdFromNetwork(userId, scope) // deferred number one
val usersFromFileDeferred = readUsersFromFile("basics/users.txt", scope) // deferred number two
val userStoredInFile = checkUserExists(
userDeferred.await(),
usersFromFileDeferred.await(),
) // combining two deferred
if (userStoredInFile) {
println("Found user in file")
}
}
scope.onStop()
}
private fun getUserByIdFromNetworkThread(userId: Int, onUserReady: (AsyncUser) -> Unit) {
Thread.sleep(3000)
onUserReady(AsyncUser(userId, "Filip", "Babic"))
}
private fun getUserByIdFromNetwork(userId: Int, scope: CoroutineScope) =
scope.async {
if (!isActive) {
return@async AsyncUser(0, "", "")
}
println("Retrieving user from network")
delay(3000)
AsyncUser(userId, "Filip", "Babic")
}
private fun readUsersFromFile(filePath: String, scope: CoroutineScope) = scope.async {
println("Reading the file of users")
delay(1000)
File(filePath)
.readLines()
.asSequence()
.filter { it.isNotEmpty() }
.map {
val data = it.split(" ") // makes it : [id, name, lastName]
if (data.size == 3) data else emptyList()
}
.filter { it.isNotEmpty() }
.map {
val userId = it[0].toInt()
val name = it[1]
val lastName = it[2]
AsyncUser(userId, name, lastName)
}
.toList()
}
private fun checkUserExists(user: AsyncUser, users: List<AsyncUser>):
Boolean {
return user in users
}
internal data class AsyncUser(
val userId: Int,
val name: String,
val lastName: String,
)
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/asyncAwait/AsyncAwaitPattern.kt | 3522808966 |
package com.coroutines.basics.asyncAwait
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
class CustomScope : CoroutineScope {
private var parentJob = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + parentJob
fun onStart() {
parentJob = Job()
}
fun onStop() {
parentJob.cancel() // You can also cancel the whole scope
// with `cancel(cause: CancellationException)`
}
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/asyncAwait/CustomScope.kt | 3642826767 |
package com.coroutines.basics.api
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlin.coroutines.suspendCoroutine
suspend fun <T : Any> getValue(provider: () -> T): T =
suspendCoroutine { continuation ->
continuation.resumeWith(Result.runCatching { provider() })
}
fun executeBackground(action: suspend () -> Unit) {
GlobalScope.launch { action() }
}
fun executeMain(action: suspend () -> Unit) {
GlobalScope.launch(context = Dispatchers.Main) { action() }
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/api/SuspendableApis.kt | 1121540676 |
package com.coroutines.basics.exceptionHandling
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
@OptIn(DelicateCoroutinesApi::class)
fun main() = runBlocking {
val launchJob = GlobalScope.launch {
println("1. Exception created via launch coroutine")
throw IndexOutOfBoundsException()
}
launchJob.join()
println("2. Joined failed job")
val deferred = GlobalScope.async {
println("3. Exception created via async coroutine")
throw ArithmeticException()
}
try {
deferred.await()
println("4. Unreachable, this statement is never executed")
} catch (e: Exception) {
println("5. Caught ${e.javaClass.simpleName}")
}
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/exceptionHandling/ExceptionHandling.kt | 1590497076 |
package com.coroutines.basics.exceptionHandling
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.supervisorScope
import java.lang.IllegalStateException
fun main() = runBlocking {
supervisorScope { // exception wont propagate upward
val result = async {
println("Throwing exception in async")
throw IllegalStateException()
}
try {
result.await()
} catch (e: Exception) {
println("Caught $e")
}
}
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/exceptionHandling/SupervisorScope.kt | 1106112676 |
package com.coroutines.basics.exceptionHandling
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val supervisor = SupervisorJob()
with(CoroutineScope(coroutineContext + supervisor)) {
val firstChild = launch {
println("First child throwing an exception")
throw ArithmeticException()
}
val secondChild = launch {
println("first child is cancelled: ${firstChild.isCancelled}")
try {
delay(5000)
} catch (e: CancellationException) {
println("Second child canelled because supervisor got cancelled.")
}
}
firstChild.join()
supervisor.cancel()
secondChild.join()
}
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/exceptionHandling/SupervisorJob.kt | 2109514013 |
package com.coroutines.basics.exceptionHandling
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.IOException
fun main() {
runBlocking {
try {
val data = getDataAsync()
println("Data received $data")
} catch (e: Exception) {
println("Caught ${e.javaClass.simpleName}")
}
}
}
suspend fun getDataAsync(): String { // callback wrapping using coroutine
return suspendCancellableCoroutine { continuation ->
getData(object : AsyncCallback {
override fun onSuccess(result: String) {
continuation.resumeWith(Result.success(result))
}
override fun onError(e: Exception) {
continuation.resumeWith(Result.failure(e))
}
})
}
}
fun getData(asyncCallback: AsyncCallback) {
// Flag used to trigger an exception
val triggerError = false
try {
// Delaying the thread for 3 seconds
Thread.sleep(3000)
if (triggerError) {
throw IOException()
} else {
// Send success
asyncCallback.onSuccess("[Beep.Boop.Beep]")
}
} catch (e: Exception) {
// send error
asyncCallback.onError(e)
}
}
// Callback
interface AsyncCallback {
fun onSuccess(result: String)
fun onError(e: Exception)
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/exceptionHandling/CallbackWrapping.kt | 3584767110 |
package com.coroutines.basics.exceptionHandling
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.lang.IllegalStateException
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println(
"Caught $exception with suppressed " +
exception.suppressed.contentToString(),
)
}
// parent job
val parentJob = GlobalScope.launch(handler) {
// child job 1
launch {
try {
delay(Long.MAX_VALUE)
} catch (e: Exception) {
println("${e.javaClass.simpleName} in Child job 1")
} finally {
throw ArithmeticException()
}
}
// child job 2
launch {
delay(100)
throw IllegalStateException()
}
delay(Long.MAX_VALUE) // delaying the parent
}
parentJob.join()
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/exceptionHandling/ExceptionHandlingForChild.kt | 1824012463 |
package com.coroutines.basics.exceptionHandling
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
@OptIn(DelicateCoroutinesApi::class)
fun main() {
runBlocking {
val callAwaitOnDeferred = false // true
val deferred = GlobalScope.async {
println("Throwing exception from async")
throw ArithmeticException("Something went wrong")
}
if (callAwaitOnDeferred) {
try {
deferred.await()
} catch (e: ArithmeticException) {
println("Caught Arithmetic Exception")
}
}
}
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/exceptionHandling/TryCatchExamination.kt | 3639442711 |
package com.coroutines.basics.exceptionHandling
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
@OptIn(DelicateCoroutinesApi::class)
fun main() {
runBlocking {
val exceptionHandler = CoroutineExceptionHandler { coroutineContext, exception ->
println("Caught $exception")
}
val job = GlobalScope.launch(exceptionHandler) {
throw AssertionError("My Custom Assertion Error!")
}
val deferred = GlobalScope.async(exceptionHandler) {
throw ArithmeticException()
}
joinAll(job, deferred)
}
}
| coroutine-ultimate-guild/basics/src/main/java/com/coroutines/basics/exceptionHandling/GlobalExceptionHandler.kt | 1262051939 |
package com.coroutines.advanced
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.coroutines.advanced.test", appContext.packageName)
}
} | coroutine-ultimate-guild/advanced/src/androidTest/java/com/coroutines/advanced/ExampleInstrumentedTest.kt | 3821889850 |
package com.coroutines.advanced
import com.coroutines.advanced.coroutineTest.contextProvider.CoroutineContextProviderImpl
import com.coroutines.advanced.coroutineTest.presentation.MainPresenter
import com.coroutines.advanced.coroutineTest.view.MainView
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertNull
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Test
class MainViewTest {
// test coroutineScope and coroutineContext
private val testCoroutineDispatcher = StandardTestDispatcher() // helps coroutines run immediately
private val testCoroutineScope = TestScope(testCoroutineDispatcher) // expose all functions to control the CoroutineDispatcher
private val testCoroutineContextProvider = CoroutineContextProviderImpl(testCoroutineDispatcher)
private val mainPresenter by lazy { MainPresenter() }
private val mainView by lazy { MainView(mainPresenter, testCoroutineContextProvider, testCoroutineScope) }
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun testFetchUserData(): Unit = testCoroutineScope.runTest {
// arrange: initial state
assertNull(mainView.userData)
// act: updating the state
mainView.fetchUserData()
// advance the time to make test pass :
// advanceTimeBy(1010) : this works and advanceUntilIdle works just fine too!
advanceUntilIdle()
// assert: checking the new state, and printing it out
assertEquals("Filip", mainView.userData?.name)
mainView.printUserData()
}
@Test
fun exampleTest() = runTest {
// acts like runBlocking but instead of actually delaying the time, it advances the test time
val deferred = async {
delay(1_000)
async {
delay(1_000)
}.await()
}
deferred.await()
}
}
| coroutine-ultimate-guild/advanced/src/test/java/com/coroutines/advanced/MainViewTest.kt | 3360455623 |
package com.coroutines.advanced.coroutinesInAndroid.ui.viewmodel
import androidx.lifecycle.ViewModel
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
import com.coroutines.advanced.coroutinesInAndroid.data.repository.DisneyRepository
import com.coroutines.advanced.coroutinesInAndroid.di.DependencyHolder
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class DisneyViewModel : ViewModel() {
// private val disneyRepo: DisneyRepository by lazy { DependencyHolder.disneyRepository }
private val _uiState = MutableStateFlow(emptyList<DisneyCharacter>())
val uiState: StateFlow<List<DisneyCharacter>>
get() = _uiState
init {
getDisneyCharacters()
}
private fun getDisneyCharacters() {
// Add the implementation here
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/viewmodel/DisneyViewModel.kt | 2906007836 |
package com.coroutines.advanced.coroutinesInAndroid.ui.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.coroutines.advanced.R
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
import com.coroutines.advanced.coroutinesInAndroid.ui.adapter.list.DisneyAdapter
import com.coroutines.advanced.databinding.ActivityNetworkingBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class DisneyActivity : AppCompatActivity() {
private lateinit var binding: ActivityNetworkingBinding
private val adapter by lazy { DisneyAdapter() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityNetworkingBinding.inflate(layoutInflater)
setContentView(binding.root)
initUi()
binding.startProcessing.setOnClickListener { fetchDisneyCharacters() }
}
private fun initUi() {
startLoadingAnimation()
binding.characterList.adapter = adapter
binding.characterList.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
}
private fun startLoadingAnimation() {
val animation = AnimationUtils.loadAnimation(this, R.anim.rotate_indefinitely)
binding.loadingAnimation.startAnimation(animation)
}
private fun showResults(characters: List<DisneyCharacter>) = with(binding) {
characterList.visibility = View.VISIBLE
uiProcessingContainer.visibility = View.GONE
adapter.setData(characters)
}
private fun fetchDisneyCharacters() {
// Create a new coroutine in the scope tied to the lifecycle of the Activity
lifecycleScope.launch(Dispatchers.IO) {
// Make the network request on a background thread
runCatching { }
.onSuccess {
// Switch to the main thread to show the results
withContext(Dispatchers.Main) {
}
}
.onFailure { it.printStackTrace() }
}
}
companion object {
fun start(from: Context) =
from.startActivity(Intent(from, DisneyActivity::class.java))
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/activity/DisneyActivity.kt | 2884256706 |
package com.coroutines.advanced.coroutinesInAndroid.ui.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.view.View
import android.view.animation.AnimationUtils
import androidx.activity.ComponentActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.coroutines.advanced.R
import com.coroutines.advanced.coroutinesInAndroid.ui.activity.ProcessingMethod.*
import com.coroutines.advanced.coroutinesInAndroid.ui.adapter.list.DisneyAdapter
import com.coroutines.advanced.databinding.ActivityBackgroundProcessingBinding
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
import com.coroutines.advanced.coroutinesInAndroid.di.DependencyHolder
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.Executors
enum class ProcessingMethod {
MAIN_THREAD, THREAD, HANDLER, HANDLER_THREAD, EXECUTOR, RX_JAVA, COROUTINES
}
class BackgroundProcessingActivity : ComponentActivity() {
// Change this variable in order to change the processing method
private var processingMethod: ProcessingMethod = THREAD
private lateinit var binding: ActivityBackgroundProcessingBinding
private var handlerThread: HandlerThread? = null
private val getCharactersRunnable by lazy { GetCharactersRunnable() }
private val adapter by lazy { DisneyAdapter() }
private var disposable: Disposable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBackgroundProcessingBinding.inflate(layoutInflater)
setContentView(binding.root)
initUi()
startLoadingAnimation()
setClickListeners()
}
private fun initUi() = with(binding) {
startLoadingAnimation()
currentProcessingMethod.text = "Processing method: ${processingMethod.name}"
characterList.adapter = adapter
characterList.layoutManager = LinearLayoutManager(
this@BackgroundProcessingActivity,
RecyclerView.VERTICAL,
false,
)
}
private fun startLoadingAnimation() {
val animation = AnimationUtils.loadAnimation(this, R.anim.rotate_indefinitely)
binding.loadingAnimation.startAnimation(animation)
}
private fun setClickListeners() {
binding.startProcessing.setOnClickListener {
startProcessing()
}
}
private fun startProcessing() {
when (processingMethod) {
MAIN_THREAD -> runUiBlockingProcessing()
THREAD -> runProcessingWithThread()
HANDLER -> runProcessingWithHandler()
HANDLER_THREAD -> runProcessingWithHandlerThread()
EXECUTOR -> runProcessingWithExecutor()
RX_JAVA -> runProcessingWithRxJava()
COROUTINES -> runProcessingWithCoroutines()
}
}
private fun runUiBlockingProcessing() {
// This will block the thread while executing
// com.coroutines.advanced.coroutineInUiLayer.common.utiles.showToast("Result: ${fibonacci(40)}")
}
private fun runProcessingWithThread() {
// Create a new Thread which will do the work
Thread(getCharactersRunnable).start()
}
private fun runProcessingWithHandler() {
// Create a Handler associated with the main thread
val handler = Handler(Looper.getMainLooper())
// Create a new thread and give it some work to do
Thread {
val characters = emptyList<DisneyCharacter>()// disneyApiService.getDisneyCharacters()
// Use the handler to show results on the main thread
handler.post {
showResults(characters)
}
}.start()
}
private fun runProcessingWithHandlerThread() {
// Create a new thread
handlerThread = HandlerThread("MyHandlerThread")
handlerThread?.let {
handlerThread?.start()
// Create a new Handler that will use HandlerThread's Looper to do its work
val handler = Handler(it.looper)
// Create a Handler with the main thread Looper
val mainHandler = Handler(Looper.getMainLooper())
// This will run on the HandlerThread created above
handler.post {
val characters = emptyList<DisneyCharacter>() //disneyApiService.getDisneyCharacters()
// Use the handler associated with the main thread to show the results
mainHandler.post {
showResults(characters)
}
}
}
}
private fun runProcessingWithExecutor() {
// Create a new Executor with a fixed thread pool and execute the Runnable
val executor = Executors.newFixedThreadPool(1)
executor.execute(getCharactersRunnable)
}
private fun runProcessingWithRxJava() {
// 1
disposable = Single.create<List<DisneyCharacter>> { emitter ->
// 2
val characters = emptyList<DisneyCharacter>()// disneyApiService.getDisneyCharacters()
emitter.onSuccess(characters)
// 3
}.subscribeOn(Schedulers.io())
// 4
.observeOn(AndroidSchedulers.mainThread())
// 5
.subscribe(::showResults, Throwable::printStackTrace)
}
private fun runProcessingWithCoroutines() {
lifecycleScope.launch(Dispatchers.IO) {
val characters = emptyList<DisneyCharacter>() //disneyApiService.getDisneyCharacters()
withContext(Dispatchers.Main) {
showResults(characters)
}
}
}
private fun showResults(characters: List<DisneyCharacter>) = with(binding) {
characterList.visibility = View.VISIBLE
uiProcessingContainer.visibility = View.GONE
adapter.setData(characters)
}
private fun fibonacci(number: Int): Long {
return if (number == 1 || number == 2) {
1
} else {
fibonacci(number - 1) + fibonacci(number - 2)
}
}
inner class GetCharactersRunnable : Runnable {
override fun run() {
val characters = emptyList<DisneyCharacter>() //disneyApiService.getDisneyCharacters()
runOnUiThread { showResults(characters) }
}
}
override fun onDestroy() {
// Dispose the disposable if it has been created
disposable?.dispose()
// Stop the HandlerThread because it's no longer needed
handlerThread?.quit()
super.onDestroy()
}
companion object {
fun start(from: Context) =
from.startActivity(Intent(from, BackgroundProcessingActivity::class.java))
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/activity/BackgroundProcessingActivity.kt | 2561981262 |
package com.coroutines.advanced.coroutinesInAndroid.ui.activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.coroutines.advanced.R
import com.coroutines.advanced.coroutinesInAndroid.ui.compose.DisneyComposeActivity
import com.coroutines.advanced.databinding.ActivityIntroBinding
class IntroActivity : AppCompatActivity() {
private lateinit var binding: ActivityIntroBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Set theme explicitly because we used another theme for the splash screen
setTheme(R.style.AppTheme)
binding = ActivityIntroBinding.inflate(layoutInflater)
setContentView(binding.root)
setClickListeners()
}
private fun setClickListeners() = with(binding) {
chapter14.setOnClickListener { BackgroundProcessingActivity.start(this@IntroActivity) }
// chapter15.setOnClickListener { UiLayerActivity.start(this@IntroActivity) }
chapter16.setOnClickListener { DisneyActivity.start(this@IntroActivity) }
compose.setOnClickListener { DisneyComposeActivity.start(this@IntroActivity) }
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/activity/IntroActivity.kt | 696071438 |
package com.coroutines.advanced.coroutinesInAndroid.ui.compose
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
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.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.coroutines.advanced.R
import com.coroutines.advanced.coroutinesInAndroid.ui.theme.DisneyExplorerTheme
@Composable
fun DisneyCharacterCard(
image: String = "",
name: String = "",
onClick: () -> Unit = {},
) {
Surface(
shape = RoundedCornerShape(16.dp),
elevation = 8.dp,
modifier = Modifier
.fillMaxWidth()
.padding(4.dp),
) {
Row(
Modifier
.padding(12.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
val painter = rememberImagePainter(data = image)
Image(
painter = painter,
stringResource(R.string.cd_character_image),
contentScale = ContentScale.Crop,
modifier = Modifier
.size(64.dp)
.clip(CircleShape),
)
Spacer(modifier = Modifier.size(20.dp))
Text(text = name, modifier = Modifier.weight(2f))
Text(
text = "Details",
modifier = Modifier
.clickable { onClick() }
.padding(8.dp)
.weight(1f),
)
}
}
}
@Preview
@Composable
fun DefaultPreview() {
DisneyExplorerTheme {
DisneyCharacterCard(name = "Mickey")
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/compose/DisneyCharacterCard.kt | 197892485 |
package com.coroutines.advanced.coroutinesInAndroid.ui.compose
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import com.coroutines.advanced.coroutinesInAndroid.ui.viewmodel.DisneyViewModel
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
class DisneyComposeActivity : ComponentActivity() {
// private val viewModel: DisneyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContent {
// DisneyExplorerTheme {
// // A surface container using the 'background' color from the theme
// Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
// MainDisneyScreen(viewModel = viewModel, lifecycle = lifecycle)
// }
// }
// }
}
companion object {
fun start(from: Context) =
from.startActivity(Intent(from, DisneyComposeActivity::class.java))
}
}
@Composable
fun MainDisneyScreen(viewModel: DisneyViewModel, lifecycle: Lifecycle) {
// remember the ui state until it changes
// val uiStateFlow = remember(viewModel.uiState) {
// Automatically starts/stops collecting based on the specified lifecycle
// viewModel.uiState.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
// }
// Collects the flow as State (Compose State)
// val charactersList by uiStateFlow.collectAsState(emptyList())
// CharacterList(characterList = charactersList)
}
@Composable
private fun CharacterList(characterList: List<DisneyCharacter>) {
LazyColumn(contentPadding = PaddingValues(16.dp)) {
items(characterList) { character ->
DisneyCharacterCard(
image = character.imageUrl,
name = character.name,
)
}
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/compose/DisneyComposeActivity.kt | 3231625194 |
package com.coroutines.advanced.coroutinesInAndroid.ui.adapter.list
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
class DisneyAdapter : RecyclerView.Adapter<CharacterViewHolder>() {
private val data: MutableList<DisneyCharacter> = mutableListOf()
fun setData(characters: List<DisneyCharacter>) {
data.clear()
data.addAll(characters)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharacterViewHolder {
return CharacterViewHolder.create(parent)
}
override fun onBindViewHolder(holder: CharacterViewHolder, position: Int) {
holder.bind(data[position])
}
override fun getItemCount() = data.size
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/adapter/list/DisneyAdapter.kt | 3657764241 |
package com.coroutines.advanced.coroutinesInAndroid.ui.adapter.list
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.coroutines.advanced.databinding.ListItemCharacterBinding
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
class CharacterViewHolder(private val binding: ListItemCharacterBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(disneyCharacter: DisneyCharacter) = with(binding) {
characterImage.load(disneyCharacter.imageUrl)
characterName.text = disneyCharacter.name
}
companion object {
fun create(parent: ViewGroup): CharacterViewHolder {
val binding = ListItemCharacterBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false,
)
return CharacterViewHolder(binding)
}
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/adapter/list/CharacterViewHolder.kt | 54557000 |
package com.coroutines.advanced.coroutinesInAndroid.ui.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.coroutines.advanced.databinding.ListItemNumberBinding
class NumbersAdapter : RecyclerView.Adapter<NumberViewHolder>() {
private val numbers = mutableListOf<Int>()
fun addNumber(number: Int) {
numbers.add(number)
notifyItemInserted(itemCount - 1)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
NumberViewHolder.create(parent)
override fun onBindViewHolder(holder: NumberViewHolder, position: Int) {
holder.bind(numbers[position])
}
override fun getItemCount() = numbers.size
override fun getItemId(position: Int) = numbers[position].toLong()
}
class NumberViewHolder(private val binding: ListItemNumberBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(number: Int) {
binding.number.text = number.toString()
}
companion object {
fun create(parent: ViewGroup): NumberViewHolder {
val binding = ListItemNumberBinding.inflate(
LayoutInflater.from(parent.context), parent,
false
)
return NumberViewHolder(binding)
}
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/adapter/NumbersAdapter.kt | 1349612627 |
package com.coroutines.advanced.coroutinesInAndroid.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
)
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/theme/Shape.kt | 820111652 |
package com.coroutines.advanced.coroutinesInAndroid.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/theme/Color.kt | 3289511850 |
package com.coroutines.advanced.coroutinesInAndroid.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200,
background = Color.Black
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200,
background = Color.White
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun DisneyExplorerTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/theme/Theme.kt | 2353994539 |
package com.coroutines.advanced.coroutinesInAndroid.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
)
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/ui/theme/Type.kt | 2529955944 |
package com.coroutines.advanced.coroutinesInAndroid
import android.app.Application
import android.content.Context
class App : Application() {
companion object {
lateinit var appContext: Context
}
override fun onCreate() {
super.onCreate()
appContext = this
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/App.kt | 1799583144 |
package com.coroutines.advanced.coroutinesInAndroid.di
import androidx.room.Room
import com.coroutines.advanced.coroutineInUiLayer.common.utiles.CoroutineContextProvider
import com.coroutines.advanced.coroutineInUiLayer.data.networking.DisneyApi
import com.coroutines.advanced.coroutinesInAndroid.App
import com.coroutines.advanced.coroutinesInAndroid.data.database.CharacterDao
import com.coroutines.advanced.coroutinesInAndroid.data.database.DisneyDatabase
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.json.Json
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
private const val BASE_URL = "http://api.disneyapi.dev/"
private const val DB_NAME = "CharactersDatabase"
/* This is a very basic and naive approach to implement Dependency Injection. But, it will suffice
for this sample project.
*/
object DependencyHolder {
val disneyApi: DisneyApi by lazy { retrofit.create(DisneyApi::class.java) }
// private val characterDao: CharacterDao by lazy { getDatabase().characterDao() }
// val disneyRepository: DisneyRepository by lazy {
// DisneyRepositoryImpl(
// // apiService,
// characterDao,
// getCoroutineContextProvider(),
// )
// }
// val apiService: DisneyApiService by lazy { DisneyApiServiceImpl(disneyApi) }
private val json = Json { ignoreUnknownKeys = true }
private val contentType = "application/json".toMediaType()
private val retrofit by lazy { buildRetrofit() }
private fun buildRetrofit() = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getOkHttpClient())
.addConverterFactory(json.asConverterFactory(contentType))
.build()
private fun getCoroutineContextProvider() = CoroutineContextProvider()
private fun getDatabase() = Room.databaseBuilder(
App.appContext,
DisneyDatabase::class.java,
DB_NAME,
).build()
private fun getOkHttpClient() = OkHttpClient.Builder()
// .apply { if (BuildConfig.DEBUG) eventListenerFactory(LoggingEventListener.Factory()) }
.addInterceptor(getLoggingInterceptor())
.build()
private fun getLoggingInterceptor(): Interceptor {
return HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/di/DependencyHolder.kt | 3204833329 |
package com.raywenderlich.android.disneyexplorer.common.utils
import android.content.Context
import android.widget.Button
import android.widget.Toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
fun Context.showToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/common/utils/Extensions.kt | 1621703040 |
package com.raywenderlich.android.disneyexplorer.common.utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlin.random.Random
object FlowUtils {
fun testDataFlow() = flow {
while (true) {
emit(Random.nextInt())
println("FLOW: Emitting item")
kotlinx.coroutines.delay(500)
}
}.flowOn(Dispatchers.Default)
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/common/utils/FlowUtils.kt | 1015811690 |
package com.raywenderlich.android.disneyexplorer.common.utils
import com.coroutines.advanced.coroutineInUiLayer.common.utiles.CoroutineContextProvider
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
open class CoroutineContextProvider {
open val mainDispatcher: CoroutineDispatcher = Dispatchers.Main
open val ioDispatcher = Dispatchers.IO
open val defaultDispatcher = Dispatchers.Default
}
class TestCoroutineContextProvider : CoroutineContextProvider() {
override val mainDispatcher = Dispatchers.Unconfined
override val ioDispatcher = Dispatchers.Unconfined
override val defaultDispatcher = Dispatchers.Unconfined
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/common/utils/CoroutineContextProvider.kt | 3197380428 |
package com.coroutines.advanced.coroutinesInAndroid.data.database
import androidx.room.Database
import androidx.room.RoomDatabase
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
@Database(entities = [DisneyCharacter::class], version = 1, exportSchema = false)
abstract class DisneyDatabase : RoomDatabase() {
// abstract fun characterDao(): CharacterDao
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/data/database/DisneyDatabase.kt | 161231677 |
package com.coroutines.advanced.coroutinesInAndroid.data.database
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
//@Dao
interface CharacterDao {
// @Insert
fun saveCharacters(characters: List<DisneyCharacter>)
// TODO: Add suspend modifier to the function and compare the results (chapter 17)
// @Query("SELECT * FROM character")
suspend fun getCharacters(): List<DisneyCharacter>
// TODO: Add a function which returns flow of data (chapter 17)
// TODO: Add a function which returns results wrapped in LiveData (chapter 18)
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/data/database/CharacterDao.kt | 2198611823 |
package com.coroutines.advanced.coroutinesInAndroid.data.repository
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
import kotlinx.coroutines.flow.Flow
interface DisneyRepository {
suspend fun getDisneyCharacters(): List<DisneyCharacter>
fun disneyCharacterFlow(): Flow<List<DisneyCharacter>>
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/data/repository/DisneyRepository.kt | 441082496 |
package com.coroutines.advanced.coroutinesInAndroid.data.repository
import com.coroutines.advanced.coroutineInUiLayer.common.utiles.CoroutineContextProvider
import com.coroutines.advanced.coroutinesInAndroid.data.database.CharacterDao
import com.coroutines.advanced.coroutinesInAndroid.data.model.DisneyCharacter
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
class DisneyRepositoryImpl(
// private val apiService: DisneyApiService,
private val characterDao: CharacterDao,
private val coroutineContextProvider: CoroutineContextProvider,
) : DisneyRepository {
override suspend fun getDisneyCharacters(): List<DisneyCharacter> {
return withContext(coroutineContextProvider.ioDispatcher) {
// val apiResponse = apiService.getCharactersSuspend()
// characterDao.saveCharacters(apiResponse)
characterDao.getCharacters()
}
}
override fun disneyCharacterFlow(): Flow<List<DisneyCharacter>> {
return flow {
// val apiResponse = apiService.getCharactersSuspend()
// characterDao.saveCharacters(apiResponse)
emit(characterDao.getCharacters())
}
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/data/repository/DisneyRepositoryImpl.kt | 3138428180 |
package com.coroutines.advanced.coroutinesInAndroid.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Entity(tableName = "character")
@Serializable
data class DisneyCharacter(
@SerialName("_id") @PrimaryKey val id: Int,
val name: String,
val imageUrl: String,
)
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/data/model/DisneyCharacter.kt | 3336605869 |
package com.coroutines.advanced.coroutinesInAndroid.data.model
import kotlinx.serialization.Serializable
@Serializable
data class CharactersResponse(val data: List<DisneyCharacter>)
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutinesInAndroid/data/model/CharactersResponse.kt | 517018795 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.delay
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val jobOne = launch {
println("Job 1: Crunching numbers [Beep.Boop.Beep]...")
delay(2000L)
}
val jobTwo = launch {
println("Job 2: Crunching numbers [Beep.Boop.Beep]...")
delay(500L)
}
// waiting for all :
joinAll(jobOne, jobTwo)
println("main: Now I can quit.")
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/JoinAllCoroutineEaxmple.kt | 1861110664 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
fun main() = runBlocking {
val result = withTimeoutOrNull(1300L) {
repeat(1000) { i ->
println("$i. Crunching numbers [Beep.Boop.Beep]...")
delay(500L)
}
"Done" // will get canceled before it produces this result
}
// Result will be null
println("Result is $result")
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/WithTimeoutOrNullExample.kt | 3920757718 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 10 && isActive) {
if (System.currentTimeMillis() >= nextPrintTime) {
println("Doing heavy work $i")
i++
nextPrintTime += 500L
}
}
}
delay(1000)
println("Cancelling coroutine")
job.cancel()
println("Main: now I can quit!")
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/CooperativeCancellation.kt | 1160843994 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val job = launch(Dispatchers.Default) {
var i = 0
while (i < 1000) {
println("Doing heavy work ${i++}")
delay(500)
}
}
delay(1200)
println("Cancelling")
job.cancel()
println("Main: Now I can quit!")
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/StdLibCancellation.kt | 4166624959 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
fun main() = runBlocking {
withTimeout(1500L) {
repeat(1000) { i ->
println("$i. Crunching numbers [Beep.Boop.Beep]...")
delay(500L)
}
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/WithTimeoutExample.kt | 1352676725 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val parentJob = launch {
val childOne = launch {
repeat(1000) { i ->
println(
"Child Coroutine 1: " +
"$i. Crunching numbers [Beep.Boop.Beep]...",
)
delay(500L)
}
}
// Handle the exception thrown from `launch`
// coroutine builder
childOne.invokeOnCompletion { exception ->
println("Child One: ${exception?.message}")
}
val childTwo = launch {
repeat(1000) { i ->
println("Child coroutine 2: $i. Crunching numbers [Beep.Boop.Beep]...")
delay(500L)
}
}
// Handle the exception thrown from `launch`
// coroutine builder
childTwo.invokeOnCompletion { exception ->
println("child two: ${exception?.message}")
}
}
delay(1200L)
println("Calling cancelChildren() on the parentJob")
parentJob.cancelChildren()
println("parentJob isActive ${parentJob.isActive}")
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/CancelChildren.kt | 3612848833 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val job = launch {
println("Crunching Numbers [Beep.Boop.Beep]...")
delay(1000L)
}
// waiting for completion :
job.join()
println("main: now i can quit ")
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/JoinCoroutineExample.kt | 2194787969 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.io.IOException
@OptIn(DelicateCoroutinesApi::class)
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught original $exception")
}
val parentJob = GlobalScope.launch(handler) {
val childJob = launch {
throw IOException()
}
try {
childJob.join()
} catch (e: CancellationException) {
println(
"Rethrowing CancellationException with original\n" +
"cause: ${e.cause}",
)
throw e
}
}
parentJob.join()
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/CancellationExceptionExample.kt | 1380503182 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val job = launch {
repeat(1000) { i ->
println("$i. Crunching numbers [Beep.Boop.Beep]...")
delay(500L)
}
}
delay(1300L)
println("main: im tired of waiting!")
job.cancelAndJoin()
println("main: now i can quit.")
}
/**
* without cancelAndJoin the launch first at the start and never stops until it
* finishes, meanwhile the outside of launch block runs after
* 1300 milli seconds
*
* with cancel and join the launch block runs only for
* 1300 milli second
*/
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/CancelAndJoinCoroutineExample.kt | 1539524482 |
package com.coroutines.advanced.manageCancellation
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
fun main() = runBlocking {
try {
withTimeout(1500L) {
repeat(1000) { i ->
println("$i. Crunching numbers [Beep.Boop.Beep]...")
delay(500L)
}
}
} catch (e: TimeoutCancellationException) {
println("Caught ${e.javaClass.simpleName}")
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/manageCancellation/TimeoutCancellationExceptionHandling.kt | 1989040729 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@OptIn(DelicateCoroutinesApi::class)
fun main() {
val sharedFlow = MutableSharedFlow<Int>(2)
sharedFlow.tryEmit(5)
sharedFlow.tryEmit(3)
sharedFlow.tryEmit(1)
sharedFlow.onEach {
println("Emitting $it")
}.launchIn(GlobalScope)
sharedFlow.onEach {
println("Hello $it")
}.launchIn(GlobalScope)
Thread.sleep(50)
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/ReplayingValues.kt | 1542283713 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
@OptIn(DelicateCoroutinesApi::class)
fun main() {
val flowOfString = flow {
// emit("") : uncomment to see an exception
for (number in 0..100) {
emit("Emitting $number")
}
}
GlobalScope.launch {
flowOfString
.map { it.split(" ") }
.map { it[1] }
// .catch { CoroutineExceptionHandler }
.catch {
it.printStackTrace()
emit("Fallback")
}
.flowOn(Dispatchers.Default)
.collect { println(it) }
}
println("the code still work")
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/TransparencyOfException.kt | 2966546253 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
fun main() {
val coroutineScope = CoroutineScope(Dispatchers.Default)
val sharedFlow = MutableSharedFlow<Int>()
sharedFlow.onEach {
println("Emitting $it")
}.launchIn(coroutineScope)
coroutineScope.launch {
sharedFlow.emit(5)
sharedFlow.emit(3)
sharedFlow.emit(1)
coroutineScope.cancel()
}
while (coroutineScope.isActive) {
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/ConsumingHotFlow.kt | 213538576 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
fun main() {
val coroutineScope = CoroutineScope(Dispatchers.Default)
val stateFlow = MutableStateFlow("Author: Filip")
println(stateFlow.value) // accesses value without subscribing
coroutineScope.launch { // access values with subscribing
stateFlow.collect {
println(it)
}
}
while (coroutineScope.isActive) {
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/StateFlow.kt | 2223006867 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@OptIn(DelicateCoroutinesApi::class)
fun main() {
val sharedFlow = MutableSharedFlow<Int>(replay = 2)
sharedFlow.onEach {
println("Emitting $it")
}.launchIn(GlobalScope)
sharedFlow.onEach {
println("Hello $it")
}.launchIn(GlobalScope)
sharedFlow.tryEmit(5)
sharedFlow.tryEmit(3)
Thread.sleep(50)
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/SharedAndStateFlow.kt | 3231341500 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.isActive
fun main() {
val coroutineScope = CoroutineScope(Dispatchers.Default)
val sharedFlow = flow {
emit(5)
emit(3)
emit(1)
Thread.sleep(50)
coroutineScope.cancel()
}.shareIn(coroutineScope, started = SharingStarted.Lazily)
sharedFlow.onEach {
println("Emitting $it")
}.launchIn(coroutineScope)
while (coroutineScope.isActive) {
}
}
/**
* using sharedIn we transform a flow into a shredFlow
* started = SharingStarted.Lazily : waits for the first subscriber
*/
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/TransformingtoSharedFlow.kt | 696609074 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
@OptIn(DelicateCoroutinesApi::class)
fun main() {
val flowOfString = flow {
for (number in 0..100) {
emit("Emitting $number")
}
}
GlobalScope.launch {
flowOfString.collect { value ->
println(value)
}
}
Thread.sleep(1000)
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/BeginningWithCoroutineFlow.kt | 1638310892 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
@OptIn(DelicateCoroutinesApi::class)
fun main() {
val flowOfString = flow {
for (number in 0..100) {
emit("Emitting $number")
}
}
GlobalScope.launch {
flowOfString
.map { it.split(" ") }
.map { it.last() }
.flowOn(Dispatchers.IO)
.onEach { delay(100) }
.flowOn(Dispatchers.Default)
.collect { value ->
println(value)
}
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/SwitchingContext.kt | 710215167 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
@OptIn(DelicateCoroutinesApi::class)
fun main() {
val flowOfString = flow {
for (number in 0..100) {
emit("Emitting $number")
}
}
GlobalScope.launch {
flowOfString
.map { it.split(" ") }
.map { it.last() }
.onEach { delay(100) }
.collect { value ->
println(value)
}
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/TransformingFlow.kt | 3200131075 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* this ends up in a exception saying: you cant change the flow concurrency
*
*/
@OptIn(DelicateCoroutinesApi::class)
fun mainBroken() {
// this is a violation :
val flowOfString = flow {
for (number in 0..100) {
GlobalScope.launch {
emit("Emitting $number")
}
}
}
GlobalScope.launch {
flowOfString.collect {
println(it)
}
}
}
@OptIn(DelicateCoroutinesApi::class)
fun main() {
val flowOfString = flow {
for (number in 0..100) {
withContext(Dispatchers.IO) {
emit("Emitting $number")
}
}
}
GlobalScope.launch {
flowOfString.collect {
println(it)
}
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/PreservingFlowContext.kt | 3835917059 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@OptIn(DelicateCoroutinesApi::class)
fun main() {
val sharedFlow = MutableSharedFlow<Int>()
sharedFlow.tryEmit(5)
sharedFlow.tryEmit(3)
sharedFlow.tryEmit(1)
sharedFlow.onEach {
println("Emitting $it")
}.launchIn(GlobalScope)
sharedFlow.onEach {
println("Hello $it")
}.launchIn(GlobalScope)
Thread.sleep(50)
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/HotStream.kt | 1382192811 |
package com.coroutines.advanced.flowOfData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
fun main() {
val coroutineScope = CoroutineScope(Dispatchers.Default)
val stateFlow = MutableStateFlow("Author: Filip")
stateFlow.value = "Author: Luka" // first way of updating: direct
stateFlow.tryEmit("FPE: Max") // second way of updating: safest
coroutineScope.launch {
stateFlow.emit("TE: Godfred") // third way
}
coroutineScope.launch {
stateFlow.collect {
println(it)
}
}
Thread.sleep(50)
coroutineScope.cancel()
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/flowOfData/ChangingStateFlow.kt | 4064268599 |
package com.coroutines.advanced.coroutineInUiLayer.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/ui/theme/Color.kt | 2981544636 |
package com.coroutines.advanced.coroutineInUiLayer.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun CoroutineUltimateGuideTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/ui/theme/Theme.kt | 2160958482 |
package com.coroutines.advanced.coroutineInUiLayer.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/ui/theme/Type.kt | 2008078448 |
package com.coroutines.advanced.coroutineInUiLayer
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.lifecycleScope
import com.coroutines.advanced.coroutineInUiLayer.ui.theme.CoroutineUltimateGuideTheme
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CoroutineUltimateGuideTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
) {
Greeting("Android")
}
}
}
}
private fun fetchDisneyCharacters() {
lifecycleScope.launch {
// apiService.getCharacters()
// .onSuccess { showResults(it.data) }
// .onFailure { showError(it) }
// }
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier,
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
CoroutineUltimateGuideTheme {
Greeting("Android")
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/MainActivity.kt | 2284331016 |
package com.coroutines.advanced.coroutineInUiLayer
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.coroutines.advanced.coroutineInUiLayer.ui.theme.CoroutineUltimateGuideTheme
import com.raywenderlich.android.disneyexplorer.common.utils.FlowUtils
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class UiLayerActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CoroutineUltimateGuideTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
) {
Greeting2("Android")
}
}
}
}
private fun runProcessingWithFlow() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
FlowUtils.testDataFlow().collect {
println("Flow: value is: $it")
}
}
}
}
private fun runProcessingWithAFlow() {
lifecycleScope.launch {
FlowUtils.testDataFlow().flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
.collect {
println("Flow: value is $it")
}
}
}
}
@Composable
fun Greeting2(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier,
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview2() {
CoroutineUltimateGuideTheme {
Greeting2("Android")
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/UiLayerActivity.kt | 2305977552 |
package com.coroutines.advanced.coroutineInUiLayer.common.utiles
import android.content.Context
import android.widget.Toast
fun Context.showToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/common/utiles/Extensions.kt | 3039705504 |
package com.coroutines.advanced.coroutineInUiLayer.common.utiles
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlin.random.Random
object FlowUtils {
fun testDataFlow() = flow {
while (true) {
emit(Random.nextInt())
println("FLOW: Emitting item")
kotlinx.coroutines.delay(500)
}
}.flowOn(Dispatchers.Default)
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/common/utiles/FlowUtils.kt | 4104891789 |
package com.coroutines.advanced.coroutineInUiLayer.common.utiles
import com.raywenderlich.android.disneyexplorer.common.utils.CoroutineContextProvider
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
open class CoroutineContextProvider {
open val mainDispatcher: CoroutineDispatcher = Dispatchers.Main
open val ioDispatcher = Dispatchers.IO
open val defaultDispatcher = Dispatchers.Default
}
class TestCoroutineContextProvider : CoroutineContextProvider() {
override val mainDispatcher = Dispatchers.Unconfined
override val ioDispatcher = Dispatchers.Unconfined
override val defaultDispatcher = Dispatchers.Unconfined
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/common/utiles/CoroutineContextProvider.kt | 2800463427 |
package com.coroutines.advanced.coroutineInUiLayer.data.networking
import com.coroutines.advanced.coroutinesInAndroid.data.model.CharactersResponse
class DisneyApiService(private val disneyApi: DisneyApi) {
suspend fun getCharacters(): Result<CharactersResponse> =
kotlin.runCatching {
disneyApi.getCharacters()
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/data/networking/DisneyApiService.kt | 3352923998 |
package com.coroutines.advanced.coroutineInUiLayer.data.networking
import com.coroutines.advanced.coroutinesInAndroid.data.model.CharactersResponse
import retrofit2.http.GET
interface DisneyApi {
@GET("characters")
suspend fun getCharacters(): CharactersResponse
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineInUiLayer/data/networking/DisneyApi.kt | 3739575896 |
package com.coroutines.advanced.sequencesAndIterators
fun main() {
val sequence = generatorFib().take(8)
sequence.forEach {
println("$it")
}
}
fun generatorFib() = sequence {
print("Suspending")
yield(0L) // Yields a value to the Iterator being built and suspends until the next value is requested.
var cur = 0L
var next = 1L
while (true) {
print("Suspending...")
yield(next)
val tmp = cur + next
cur = next
next = tmp
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/sequencesAndIterators/GeneratingInfiniteSequence.kt | 1331909431 |
package com.coroutines.advanced.sequencesAndIterators
fun main() {
val list = listOf(1, 2, 3)
list.filter {
print("filter,")
it > 0
}.map {
print("map, ")
it.toString()
}.forEach {
print("forEach, ")
}
}
/**
* Collection interface inherits from Iterable interface.
* Iterable<E> is non-lazy by default or eager-evaluated.
* Thus, all collections are eager-evaluated.
*/
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/sequencesAndIterators/EagerEvaluationIterable.kt | 1335474992 |
package com.coroutines.advanced.sequencesAndIterators
fun main() {
val sequence = singleValueExample()
sequence.forEach {
println(it)
}
}
fun singleValueExample() = sequence {
println("Printing first value")
yield("Apple")
println("printing second value")
yield("Orange")
println("printing third value")
yield("Banana")
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/sequencesAndIterators/YieldInSequence.kt | 668070804 |
package com.coroutines.advanced.sequencesAndIterators
fun main() {
val sequence = iterableExample()
sequence.forEach {
print("$it ")
}
}
fun iterableExample() = sequence {
yieldAll(1..5)
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/sequencesAndIterators/YieldAllInSequence.kt | 4110787874 |
package com.coroutines.advanced.sequencesAndIterators
fun main() {
val sequence = sequenceExample().take(10)
sequence.forEach {
print("$it ")
}
}
fun sequenceExample() = sequence {
yieldAll(generateSequence(2) { it * 2 })
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/sequencesAndIterators/YieldAllInfinitSequence.kt | 3213479910 |
package com.coroutines.advanced.sequencesAndIterators
fun main() {
val list = listOf(1, 2, 3)
list.asSequence().filter {
print("filter, ")
it > 0
}.map {
print("map, ")
}.forEach {
print("forEach, ")
}
}
/**
* Sequence is similar to Iterable from Java, except it performs lazily whenever possible.
* The key difference lies in the semantics and the implementation of the Standard Library
* extension functions for Iterable and Sequence, which both have a method called iterator.
*
*/
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/sequencesAndIterators/LazyEvalutionSequence.kt | 847482073 |
package com.coroutines.advanced.coroutineTest.contextProvider
import kotlin.coroutines.CoroutineContext
class CoroutineContextProviderImpl(private val context: CoroutineContext) : CoroutineContextProvider {
override fun context(): CoroutineContext = context
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineTest/contextProvider/CoroutineContextProviderImpl.kt | 1749024753 |
package com.coroutines.advanced.coroutineTest.contextProvider
import kotlin.coroutines.CoroutineContext
interface CoroutineContextProvider {
fun context(): CoroutineContext
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineTest/contextProvider/CoroutineContextProvider.kt | 854915555 |
package com.coroutines.advanced.coroutineTest.model
data class User(val id: String, val name: String)
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineTest/model/User.kt | 721662774 |
package com.coroutines.advanced.coroutineTest.view
import com.coroutines.advanced.coroutineTest.contextProvider.CoroutineContextProvider
import com.coroutines.advanced.coroutineTest.model.User
import com.coroutines.advanced.coroutineTest.presentation.MainPresenter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
class MainView(
private val presenter: MainPresenter,
private val contextProvider: CoroutineContextProvider,
private val coroutineScope: CoroutineScope,
) {
var userData: User? = null
/**
* Fetch user data:
* context and scope for coroutine shouldn't be hardcoded so that we can pass
* any scope that we want : actual scope for actual code and test scope for
* test code
*
*/
fun fetchUserData() {
coroutineScope.launch(contextProvider.context()) {
userData = presenter.getUser("101")
}
}
fun printUserData() {
println(userData)
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineTest/view/MainView.kt | 3025264897 |
package com.coroutines.advanced.coroutineTest.presentation
import com.coroutines.advanced.coroutineTest.model.User
import kotlinx.coroutines.delay
class MainPresenter {
suspend fun getUser(userId: String): User {
delay(1000)
return User(userId, "Filip")
}
}
| coroutine-ultimate-guild/advanced/src/main/java/com/coroutines/advanced/coroutineTest/presentation/MainPresenter.kt | 1156455168 |
package com.example.coroutineultimateguide
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.coroutineultimateguide", appContext.packageName)
}
} | coroutine-ultimate-guild/app/src/androidTest/java/com/example/coroutineultimateguide/ExampleInstrumentedTest.kt | 1411328074 |
package com.example.coroutineultimateguide
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | coroutine-ultimate-guild/app/src/test/java/com/example/coroutineultimateguide/ExampleUnitTest.kt | 2526844276 |
package com.example.coroutineultimateguide.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | coroutine-ultimate-guild/app/src/main/java/com/example/coroutineultimateguide/ui/theme/Color.kt | 862360906 |
package com.example.coroutineultimateguide.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun CoroutineUltimateGuideTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | coroutine-ultimate-guild/app/src/main/java/com/example/coroutineultimateguide/ui/theme/Theme.kt | 1433903497 |
package com.example.coroutineultimateguide.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | coroutine-ultimate-guild/app/src/main/java/com/example/coroutineultimateguide/ui/theme/Type.kt | 2976983348 |
package com.example.coroutineultimateguide
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.coroutineultimateguide.ui.theme.CoroutineUltimateGuideTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CoroutineUltimateGuideTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier,
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
CoroutineUltimateGuideTheme {
Greeting("Android")
}
}
| coroutine-ultimate-guild/app/src/main/java/com/example/coroutineultimateguide/MainActivity.kt | 2926123868 |
package com.example.brainrealm
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.brainrealm", appContext.packageName)
}
} | BrainRealm/app/src/androidTest/java/com/example/brainrealm/ExampleInstrumentedTest.kt | 3682388152 |
package com.example.brainrealm
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | BrainRealm/app/src/test/java/com/example/brainrealm/ExampleUnitTest.kt | 3224982315 |
package com.example.brainrealm.Database
import android.net.Uri
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.brainrealm.Models.UserModel
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.QuerySnapshot
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.UploadTask
class UserRepository {
private val firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance()
private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
private val storageReference = FirebaseStorage.getInstance().reference
// Sign in user with email and password
fun signIn(email: String, password: String): Task<AuthResult> {
return firebaseAuth.signInWithEmailAndPassword(email, password)
}
// Create a new user with email and password
fun createUser(email: String, password: String): Task<AuthResult> {
return firebaseAuth.createUserWithEmailAndPassword(email, password)
}
// Upload user image to Firebase Storage
fun uploadImage(imageUri: Uri, userId: String): UploadTask {
val userImageRef = storageReference.child("user_images/$userId.jpg")
return userImageRef.putFile(imageUri)
}
// Get user data from Firestore
fun getUserData(userId: String): LiveData<UserModel?> {
val userData = MutableLiveData<UserModel?>()
// Create a reference to the Firestore document
val userDocRef = FirebaseFirestore.getInstance().collection("users").document(userId)
// Retrieve data from userDocRef
userDocRef.get()
.addOnSuccessListener { document ->
if (document.exists()) {
// Convert the document data to UserModel
val userModel = document.toObject(UserModel::class.java)
// If UserModel is not null, create a new UserModel with necessary updates
val updatedUserModel = userModel?.copy(fullName = document.getString("fullName"))
userData.value = updatedUserModel
} else {
// If no document in Firestore or an error occurs, update LiveData with null value
userData.value = null
}
}
.addOnFailureListener { exception ->
// Update LiveData with null value in case of an error
userData.value = null
}
return userData
}
// Get all users from Firestore
fun getAllUsers(): LiveData<List<UserModel>> {
val usersLiveData = MutableLiveData<List<UserModel>>()
// Retrieve all documents from the Firestore collection
FirebaseFirestore.getInstance().collection("users")
.get()
.addOnSuccessListener { documents ->
val userList = mutableListOf<UserModel>()
for (document in documents) {
// Convert each document to UserModel and add to the list
val userModel = document.toObject(UserModel::class.java)
userList.add(userModel)
}
Log.d("repoTest", userList.size.toString())
// Update LiveData
usersLiveData.value = userList
}
.addOnFailureListener { exception ->
// Handle operations in case of an error here
Log.e("Firestore", "Error getting all users: $exception")
}
return usersLiveData
}
// Get all images for a specific user from Firebase Storage
fun getAllImagesForUser(userId: String): LiveData<List<String>> {
val imagesLiveData = MutableLiveData<List<String>>()
// Get the Firebase Storage reference
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference
// Get the UID of the current user
val currentUserId = userId
// Path where the user's profile image is stored
val imagesPath = "user_images/$currentUserId.jpg"
// Retrieve all images from a specific directory in Storage
storageRef.child(imagesPath)
.listAll()
.addOnSuccessListener { result ->
val imageList = result.items.map { it.toString() }
Log.d("imageTestRepo", imageList.size.toString())
imagesLiveData.value = imageList
}
.addOnFailureListener { exception ->
// Handle operations in case of an error here
Log.e("FirebaseStorage", "Error getting user images: $exception")
}
return imagesLiveData
}
}
| BrainRealm/app/src/main/java/com/example/brainrealm/Database/UserRepository.kt | 1785048252 |
package com.example.brainrealm
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import androidx.lifecycle.ViewModelProvider
import com.example.brainrealm.Adapters.LeaderListAdapter
import com.example.brainrealm.Models.UserModel
import com.example.brainrealm.Models.UserViewModel
import com.example.brainrealm.databinding.ActivityNotificationsBinding
import com.example.brainrealm.databinding.ActivityQuestionBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.storage.FirebaseStorage
import com.squareup.picasso.Picasso
class Notifications : AppCompatActivity() {
lateinit var binding : ActivityNotificationsBinding
private lateinit var userViewModel: UserViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityNotificationsBinding.inflate(layoutInflater)
setContentView(binding.root)
userViewModel = ViewModelProvider(this).get(UserViewModel::class.java)
val currentUser = FirebaseAuth.getInstance().currentUser
val userId = currentUser?.uid.orEmpty()
userViewModel.getUserData().observe(this, { userData ->
userData?.let {
updateUI(it)
}
})
loadImageFromFirebaseStorage(userId.toString() , binding.notificationsUseImage)
}
private fun updateUI(userModel: UserModel) {
binding.notificationsCoin.text = userModel.coin.toString()
Log.d("salam",userModel.fullName.toString())
binding.notificationsFullName.text = userModel.fullName.toString()
}
fun loadImageFromFirebaseStorage(userId: String?, imageView: ImageView) {
// Firebase Storage referansını al
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference
// Kullanıcının UID'sini al
val currentUserId = userId ?: FirebaseAuth.getInstance().currentUser?.uid
// Kullanıcının profil resminin bulunduğu yol
val imagePath = "user_images/$currentUserId.jpg"
// Storage'de bulunan resmin referansını al
val imageRef = storageRef.child(imagePath)
// Resmin URL'sini al
imageRef.downloadUrl
.addOnSuccessListener { uri ->
val imageUrl = uri.toString()
// imageUrl'i kullanarak ImageView'e resmi yükle (örneğin Picasso kütüphanesi kullanılabilir)
// Not: Picasso kullanmak için build.gradle dosyanıza şu bağımlılığı ekleyin: implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.get().load(imageUrl).into(imageView)
}
.addOnFailureListener { exception ->
// Hata durumunda işlemleri burada yönetebilirsiniz
Log.e("FirebaseStorage", "Error getting image URL: $exception")
}
}
} | BrainRealm/app/src/main/java/com/example/brainrealm/Notifications.kt | 2013758668 |
package com.example.brainrealm
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.example.brainrealm.Models.UserViewModel
import com.example.brainrealm.databinding.ActivitySettingsBinding
import com.google.firebase.auth.FirebaseAuth
private const val PREFS_NAME = "MyPreferences"
@Suppress("DEPRECATION")
class Settings : AppCompatActivity() {
lateinit var binding : ActivitySettingsBinding
private lateinit var userViewModel: UserViewModel
private val PICK_IMAGE_REQUEST = 1
private val userId = FirebaseAuth.getInstance().currentUser?.uid
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySettingsBinding.inflate(layoutInflater)
setContentView(binding.root)
userViewModel = ViewModelProvider(this).get(UserViewModel::class.java)
fullNameSave(userId.toString() , "Mehdi Israfilov")
startImagePicker()
}
private fun startImagePicker() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
startActivityForResult(intent, PICK_IMAGE_REQUEST)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null) {
val imageUri: Uri? = data.data
if (imageUri != null) {
userViewModel.uploadImage(imageUri, userId.toString())
} else {
Toast.makeText(this, "Seçilen resim URI'si null.", Toast.LENGTH_SHORT).show()
}
}
}
private fun fullNameSave(userId: String ,fullName: String) {
val sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString(userId, fullName)
editor.apply()
}
} | BrainRealm/app/src/main/java/com/example/brainrealm/Settings.kt | 1436421001 |
package com.example.brainrealm
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import com.example.brainrealm.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Load Animation
val rocketAnimation = AnimationUtils.loadAnimation(this, R.anim.rocket_animation)
// Set Animation Listener
rocketAnimation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {
// Animasyon başladığında yapılacak işlemler (isteğe bağlı)
}
override fun onAnimationEnd(animation: Animation?) {
// Animasyon bittiğinde yapılacak işlemler
startLoginActivity()
}
override fun onAnimationRepeat(animation: Animation?) {
// Animasyon tekrarlandığında yapılacak işlemler (isteğe bağlı)
}
})
// Start Animation
binding.splashScreenRocket.startAnimation(rocketAnimation)
}
private fun startLoginActivity() {
val intent = Intent(this, Login::class.java)
startActivity(intent)
finish()
}
} | BrainRealm/app/src/main/java/com/example/brainrealm/MainActivity.kt | 379228151 |
package com.example.brainrealm
data class QuestionModel(val text: String, val options: List<String>, val correctAnswer: String)
| BrainRealm/app/src/main/java/com/example/brainrealm/QuestionModel.kt | 680330694 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.