Last active
May 3, 2020 14:16
-
-
Save pavlospt/f23d50c78e3828f1681162d2d0e542f5 to your computer and use it in GitHub Desktop.
FlowUseCase.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface ObservableUseCase<Type> { | |
val dispatcher: CoroutineDispatcher | |
fun observe(): Flow<Type> | |
} | |
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class) | |
abstract class FlowUseCase<Type : Any, Params : Any> : ObservableUseCase<Type> { | |
private val channel = ConflatedBroadcastChannel<Params>() | |
operator fun invoke(params: Params) = channel.sendBlocking(params) | |
protected abstract fun doWork(params: Params): Flow<Type> | |
fun produce(params: Params): Flow<Type> = doWork(params = params) | |
.flowOn(dispatcher) | |
override fun observe(): Flow<Type> = channel.asFlow() | |
.distinctUntilChanged() | |
.flatMapLatest { doWork(it) } | |
.flowOn(dispatcher) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment