Skip to content

Instantly share code, notes, and snippets.

@pavlospt
Last active May 3, 2020 14:16
Show Gist options
  • Save pavlospt/f23d50c78e3828f1681162d2d0e542f5 to your computer and use it in GitHub Desktop.
Save pavlospt/f23d50c78e3828f1681162d2d0e542f5 to your computer and use it in GitHub Desktop.
FlowUseCase.kt
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