Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Workflow should throw meaningful error on Node destruction #353

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package com.badoo.ribs.rx2.workflows

import androidx.annotation.VisibleForTesting
import androidx.lifecycle.Lifecycle
import com.badoo.ribs.core.Node
import com.badoo.ribs.core.modality.BuildParams
import com.badoo.ribs.core.plugin.Plugin
import com.badoo.ribs.core.view.RibView
import com.badoo.ribs.core.view.ViewFactory
import com.jakewharton.rxrelay2.BehaviorRelay
import com.jakewharton.rxrelay2.PublishRelay
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
import kotlin.reflect.KClass

open class RxWorkflowNode<V : RibView>(
buildParams: BuildParams<*>,
Expand All @@ -21,55 +25,91 @@ open class RxWorkflowNode<V : RibView>(
plugins = plugins
) {

private val childrenAttachesRelay: PublishRelay<Node<*>>? = PublishRelay.create()
val childrenAttaches: Observable<Node<*>>? = childrenAttachesRelay?.hide()
val detachSignal: BehaviorRelay<Unit> = BehaviorRelay.create()
private val childrenAttachesRelay: PublishRelay<Node<*>> = PublishRelay.create()
private val detachSignalRelay: BehaviorRelay<Unit> = BehaviorRelay.create()

protected val childrenAttaches: Observable<Node<*>> = childrenAttachesRelay.hide()

// Flowable to use in takeUntil()
protected val detachSignal: Flowable<Unit> = detachSignalRelay.toFlowable(BackpressureStrategy.LATEST)

override fun onAttachChildNode(child: Node<*>) {
super.onAttachChildNode(child)
childrenAttachesRelay?.accept(child)
childrenAttachesRelay.accept(child)
}

override fun onDestroy(isRecreating: Boolean) {
super.onDestroy(isRecreating)
detachSignal.accept(Unit)
detachSignalRelay.accept(Unit)
}

/**
* Executes an action and remains on the same hierarchical level
* Executes an action and remains on the same hierarchical level.
*
* @return the current workflow element
* @throws NodeIsNotAvailableForWorkflowException when execution is not possible
*/
protected inline fun <reified T> executeWorkflow(
crossinline action: () -> Unit
): Single<T> = Single.fromCallable {
action()
this as T
@Suppress("UNCHECKED_CAST")
protected fun <T> executeWorkflow(
action: () -> Unit
): Single<T> = Single.defer {
throwExceptionSingleIfDestroyed<T>() ?: Single.fromCallable {
action()
this as T
}
}
.takeUntil(detachSignal.firstOrError())

@VisibleForTesting
internal inline fun <reified T> executeWorkflowInternal(
crossinline action: () -> Unit
): Single<T> = executeWorkflow(action)
/**
* Executes an action and remains on the same hierarchical level.
* If execution is not possible returns nothing.
*
* @return the current workflow element
*/
protected fun <T> maybeExecuteWorkflow(
action: () -> Unit
): Maybe<T> =
executeWorkflow<T>(action)
.toMaybe()
.onErrorComplete { it is NodeIsNotAvailableForWorkflowException }
.takeUntil(detachSignal)

/**
* Executes an action and transitions to another workflow element
* Executes an action and transitions to another workflow element.
*
* @param action an action that's supposed to result in the attach of a child (e.g. router.push())
* @return the child as the expected workflow element, or error if expected child was not found
* @throws NodeIsNotAvailableForWorkflowException when execution is not possible
*/
protected inline fun <reified T : Any> attachWorkflow(
noinline action: () -> Unit
): Single<T> = attachWorkflow(T::class, action)

/**
* Executes an action and transitions to another workflow element.
* If execution is not possible returns nothing.
*
* @param action an action that's supposed to result in the attach of a child (e.g. router.push())
* @return the child as the expected workflow element, or error if expected child was not found
*/
@SuppressWarnings("LongMethod")
protected inline fun <reified T> attachWorkflow(
crossinline action: () -> Unit
): Single<T> = Single.fromCallable {
protected inline fun <reified T : Any> maybeAttachWorkflow(
noinline action: () -> Unit
): Maybe<T> =
attachWorkflow(T::class, action)
.toMaybe()
.onErrorComplete { it is NodeIsNotAvailableForWorkflowException }
.takeUntil(detachSignal)

protected fun <T : Any> attachWorkflow(
clazz: KClass<T>,
action: () -> Unit
): Single<T> = Single.defer {
throwExceptionSingleIfDestroyed<T>()?.also { return@defer it }
action()
val childNodesOfExpectedType = children.filterIsInstance<T>()
val childNodesOfExpectedType = children.filterIsInstance(clazz.java)
if (childNodesOfExpectedType.isEmpty()) {
Single.error<T>(
Single.error(
IllegalStateException(
"Expected child of type [${T::class.java}] was not found after executing action. " +
"Expected child of type [${clazz.java}] was not found after executing action. " +
"Check that your action actually results in the expected child. " +
"Child count: ${children.size}. " +
"Last child is: [${children.lastOrNull()}]. " +
Expand All @@ -80,33 +120,57 @@ open class RxWorkflowNode<V : RibView>(
Single.just(childNodesOfExpectedType.last())
}
}
.flatMap { it }
.takeUntil(detachSignal.firstOrError())

@VisibleForTesting
internal inline fun <reified T> attachWorkflowInternal(
crossinline action: () -> Unit
): Single<T> = attachWorkflow(action)
/**
* Waits until a certain child is attached and returns it as the expected workflow element,
* or returns it immediately if it's already available.
*
* @return the child as the expected workflow element
* @throws NodeIsNotAvailableForWorkflowException when execution is not possible
*/
protected inline fun <reified T : Any> waitForChildAttached(): Single<T> =
waitForChildAttached(T::class)

/**
* Waits until a certain child is attached and returns it as the expected workflow element, or
* returns it immediately if it's already available.
* Waits until a certain child is attached and returns it as the expected workflow element,
* or returns it immediately if it's already available.
* If execution is not possible returns nothing.
*
* @return the child as the expected workflow element
*/
protected inline fun <reified T> waitForChildAttached(): Single<T> =
Single.fromCallable {
val childNodesOfExpectedType = children.filterIsInstance<T>()
protected inline fun <reified T : Any> maybeWaitForChildAttached(): Maybe<T> =
waitForChildAttached(T::class)
.toMaybe()
.onErrorComplete { it is NodeIsNotAvailableForWorkflowException }
.takeUntil(detachSignal)

protected fun <T : Any> waitForChildAttached(
clazz: KClass<T>,
): Single<T> =
Single.defer {
throwExceptionSingleIfDestroyed<T>()?.also { return@defer it }
val childNodesOfExpectedType = children.filterIsInstance(clazz.java)
if (childNodesOfExpectedType.isEmpty()) {
childrenAttaches?.ofType(T::class.java)?.firstOrError()
childrenAttaches.ofType(clazz.java)?.firstOrError()
} else {
Single.just(childNodesOfExpectedType.last())
}
}
.flatMap { it }
.takeUntil(detachSignal.firstOrError())

@VisibleForTesting
internal inline fun <reified T> waitForChildAttachedInternal(): Single<T> =
waitForChildAttached()
private fun <T> skipExecutionIfDestroyed(): Maybe<T>? =
if (lifecycle.currentState > Lifecycle.State.DESTROYED) {
Maybe.empty()
} else {
null
}

private fun <T> throwExceptionSingleIfDestroyed(): Single<T>? =
if (lifecycle.currentState == Lifecycle.State.DESTROYED) {
Single.error(NodeIsNotAvailableForWorkflowException("Node $this is already destroyed, further execution is meaningless"))
} else {
null
}

class NodeIsNotAvailableForWorkflowException(message: String) : IllegalStateException(message)

}
Loading