Skip to content

Commit

Permalink
Use custom ComposeCoroutineScope instead of LifecycleScope in Jetpack…
Browse files Browse the repository at this point in the history
… Compose Example
  • Loading branch information
floschu committed May 21, 2020
1 parent 75a61b1 commit 6d22578
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.compose.Composable
import androidx.compose.getValue
import androidx.lifecycle.lifecycleScope
import androidx.ui.core.ContextAmbient
import androidx.ui.core.LifecycleOwnerAmbient
import androidx.ui.core.setContent
import androidx.ui.foundation.Text
import androidx.ui.foundation.isSystemInDarkTheme
Expand All @@ -29,7 +27,7 @@ internal class AppActivity : ComponentActivity() {

@Composable
private fun AppScreen() {
val controller = LifecycleOwnerAmbient.current.lifecycleScope.createCounterController()
val controller = ComposeCoroutineScope().createCounterController()
MaterialTheme(colors = AppColors.currentColorPalette) {
Scaffold(
topAppBar = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,26 @@ package at.florianschuster.control.androidcountercomposeexample
import androidx.compose.Composable
import androidx.compose.State
import androidx.compose.collectAsState
import androidx.compose.onDispose
import androidx.compose.remember
import at.florianschuster.control.Controller
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlin.coroutines.CoroutineContext

/**
* Creates a [CoroutineScope] with [coroutineContext] that lives until [onDispose].
*/
@Composable
internal fun ComposeCoroutineScope(
coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.Main.immediate
): CoroutineScope {
val scope = remember(coroutineContext) { CoroutineScope(coroutineContext) }
onDispose { scope.cancel() }
return scope
}

/**
* Collects values from the [Controller.state] and represents its latest value via [State].
Expand Down

0 comments on commit 6d22578

Please sign in to comment.