使用Arrow-kt IO.fx泄漏Android UI {}

时间:2019-12-10 13:33:32

标签: android arrow-kt

我的Android应用程序中具有以下viewModel代码

fun perform(operation: Action.Operation, sideEffects: (List<SideEffect>) -> Unit, render: (Reaction<String>) -> Unit): IO<Unit> = IO.fx {

    !effect(Dispatchers.Main) { sideEffects(operation.sideEffects) }
    val response = !effect(Dispatchers.IO) { repository.network(operation) }
    !effect(Dispatchers.Main) { sideEffects(response.sideEffects) }
    !effect(Dispatchers.Main) { render(response) }
}

其中sideEffectsrender函数与调用方Activity相似,

private val sideEffects: (List<SideEffect>) -> Unit = { sideEffects ->
    sideEffects.forEach { sideEffect ->
        Timber.e("$sideEffect")
        val exhaustive = when (sideEffect) {
            is SideEffect.UiSideEffect.Inactive -> {
                mProgressBar.visibility = View.GONE
            }
            is SideEffect.UiSideEffect.Active -> {
                mProgressBar.visibility = View.VISIBLE
            }
            is SideEffect.UiSideEffect.Enable -> Timber.d("SIDE EFFECT:: TODO() $sideEffect")
            is SideEffect.UiSideEffect.Disable -> Timber.d("SIDE EFFECT:: TODO() $sideEffect")
            is SideEffect.Logging.Log -> Timber.d("SIDE EFFECT:: {logging} ${sideEffect.message}")
            is SideEffect.Analytical.Analytics -> Timber.d("SIDE EFFECT:: TODO() $sideEffect")
        }
    }
}

我的活动从其onCreate()方法调用perform方法

private lateinit var viewModel: MainViewModel

private lateinit var textView: TextView
private lateinit var mProgressBar: ProgressBar

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    textView = findViewById(R.id.hello_world_tv)
    mProgressBar = findViewById(R.id.progress_bar_cyclic)

    viewModel = ViewModelProviders.of(this)[MainViewModel::class.java]

    val cancel = viewModel.perform(Action.Operation(), sideEffects, render).unsafeRunAsyncCancellable { either ->
        when (either) {
            is Either.Left -> {
                Timber.e("oh Dear!!!! ${either.a}")
                //Show Error!!!
            }

            is Either.Right -> {
                Timber.e("Everything Worked correctly ${either.b}")
            }
        }
    }
}

这是一种安全的方法吗?

我将对TextView和ProgressBar的引用传递到viewModel上是否重要?

0 个答案:

没有答案