Created
February 18, 2019 12:10
-
-
Save rcmkt/15e0388fe63d98f35fa04e88977872c2 to your computer and use it in GitHub Desktop.
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
// Набор эвентов в файле Events.kt | |
interface Event | |
class OpenLinkEvent(val link: String) : Event | |
class ShowSnackbarEvent(val message: String) : Event | |
class ShareEvent(val link: String) : Event | |
class OpenEmailAppEvent(val email: String) : Event | |
// CommandsLiveData.kt | |
class CommandsLiveData<T> : MutableLiveData<ConcurrentLinkedQueue<T>>() { | |
fun onNext(value: T) { | |
var commands = getValue() | |
if (commands == null) { | |
commands = ConcurrentLinkedQueue<T>() | |
} | |
commands.add(value) | |
setValue(commands) | |
} | |
} | |
// BaseViewModel.kt | |
abstract class BaseViewModel : ViewModel() { | |
val events = CommandsLiveData<Event>() | |
private val compositeDisposable by lazy { CompositeDisposable() } | |
override fun onCleared() { | |
LeakDetectorUtils.watch(this) | |
clearSubscriptions() | |
super.onCleared() | |
} | |
fun clearSubscriptions() = compositeDisposable.clear() | |
protected fun Disposable.autoDispose(): Disposable { | |
compositeDisposable.add(this) | |
return this | |
} | |
} | |
// LyfecycleExt.kt | |
inline fun <reified T : Any, reified L : CommandsLiveData<T>> Fragment.observe(liveData: L, noinline block: (T) -> Unit) { | |
liveData.observe(viewLifecycleOwner, Observer<ConcurrentLinkedQueue<T>> { commands -> | |
if (commands == null) { | |
return@Observer | |
} | |
var command: T? | |
do { | |
command = commands.poll() | |
if (command != null) { | |
block.invoke(command) | |
} | |
} while (command != null) | |
}) | |
} | |
// Подписка на евенты | |
observe(viewModel.events, ::handleEvent) | |
private fun handleEvent(event: Event) { | |
when (event) { | |
is OpenLinkEvent -> AndroidDeviceUtils.openLinkInBrowser(requireContext(), event.link) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment