Skip to content

Instantly share code, notes, and snippets.

View ahmedrizwan's full-sized avatar
🚀
Remote

Ahmed Rizwan ahmedrizwan

🚀
Remote
View GitHub Profile
Observable.fromPublisher<String> {
it.onNext("Doing a network call!")
Thread.sleep(1000) // Long running process
it.onError(Exception()) // Some error thrown
}.retryWhen { errors ->
errors.zipWith(Observable.range(1, 3) // Zip error observable with a range one
.concatMap { retryCount ->
Observable.timer(retryCount.toLong() * 10, TimeUnit.SECONDS)
}
)
sealed class UIState<out R> {
object Loading : UIState<Nothing>()
object Retrying : UIState<Nothing>()
object SwipeRefreshing : UIState<Nothing>()
data class Success<T>(val data: T) : UIState<T>()
data class Failure(val exception: Exception) : UIState<Nothing>()
data class SwipeRefreshFailure(val exception: Exception) : UIState<Nothing>()
}
sealed class Action {
object Load : Action()
object SwipeRefresh : Action()
object Retry : Action()
}
class ActionStateLiveData<T>(
private val coroutineContext: CoroutineContext,
fetchData: (suspend () -> Response<T>)
) {
private val action = MutableLiveData<Action>()
private var data: T? = null // backing data
val state = action.switchMap {
liveData(context = coroutineContext) {
when (action.value) {
@ahmedrizwan
ahmedrizwan / MainActivity.kt
Last active May 27, 2020 11:15
Jetpack Compose Calculator
setContent {
MaterialTheme(colors = lightThemeColors) {
WithConstraints { constraints, _ ->
val boxHeight = with(DensityAmbient.current) { constraints.maxHeight.toDp() }
val boxWidth = with(DensityAmbient.current) { constraints.maxWidth.toDp() }
Content(
constraints = constraints,
boxHeight = boxHeight,
boxWidth = boxWidth
)
class Drag(
val position: AnimatedFloat,
val flingConfig: FlingConfig
)
// Side drag
val sideMin = 90.dp
val sideMax = boxWidth - 30.dp
val (sideMinPx, sideMaxPx) = with(DensityAmbient.current) {
sideMin.toPx().value to sideMax.toPx().value
}
val sideFlingConfig = AnchorsFlingConfig(listOf(sideMinPx, sideMaxPx))
val sidePosition = animatedFloat(sideMaxPx)
sidePosition.setBounds(sideMinPx, sideMaxPx)
// Top drag
val topStart = -(constraints.maxHeight.value / 1.4f)
val topMax = 0.dp
val topMin = -(boxHeight / 1.4f)
val (topMinPx, topMaxPx) = with(DensityAmbient.current) {
topMin.toPx().value to topMax.toPx().value
}
val topFlingConfig = AnchorsFlingConfig(listOf(topMinPx, topMaxPx))
val topPosition = animatedFloat(topStart) // for dragging state
topPosition.setBounds(topMinPx, topMaxPx)
@Composable
fun TopView(
boxHeight: Dp,
drag: Drag
) {
val position = drag.position
val flingConfig = drag.flingConfig
val yOffset = with(DensityAmbient.current) { position.value.toDp() }
val scrollerPosition = ScrollerPosition()
// scroll the history list to bottom when dragging the top panel
@Composable
fun DimOverlay(alpha: Int) {
Box(modifier = Modifier.fillMaxSize(), backgroundColor = Color(50, 50, 50, alpha))
}