Convert CompletableViewModels to Kotlin

pull/1051/head
Alex Baker 4 years ago
parent 919ba42098
commit dbba2e0e6f

@ -1,12 +0,0 @@
package org.tasks.activities;
import com.google.api.services.tasks.model.TaskList;
import com.todoroo.astrid.gtasks.api.GtasksInvoker;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class CreateListViewModel extends CompletableViewModel<TaskList> {
void createList(GtasksInvoker invoker, String account, String name) {
run(() -> invoker.forAccount(account).createGtaskList(name));
}
}

@ -0,0 +1,11 @@
package org.tasks.activities
import com.google.api.services.tasks.model.TaskList
import com.todoroo.astrid.gtasks.api.GtasksInvoker
import org.tasks.ui.CompletableViewModel
class CreateListViewModel : CompletableViewModel<TaskList?>() {
fun createList(invoker: GtasksInvoker, account: String?, name: String?) {
run { invoker.forAccount(account!!).createGtaskList(name) }
}
}

@ -22,6 +22,7 @@ import com.todoroo.astrid.service.TaskDeleter;
import dagger.hilt.android.AndroidEntryPoint;
import dagger.hilt.android.qualifiers.ApplicationContext;
import javax.inject.Inject;
import kotlin.Unit;
import org.tasks.R;
import org.tasks.data.GoogleTaskAccount;
import org.tasks.data.GoogleTaskList;
@ -206,7 +207,7 @@ public class GoogleTaskListSettingsActivity extends BaseListSettingsActivity {
return !getNewName().equals(gtasksList.getTitle());
}
private void onListCreated(TaskList taskList) {
private Unit onListCreated(TaskList taskList) {
gtasksList.setRemoteId(taskList.getId());
gtasksList.setTitle(taskList.getTitle());
gtasksList.setColor(selectedColor);
@ -215,6 +216,7 @@ public class GoogleTaskListSettingsActivity extends BaseListSettingsActivity {
setResult(
RESULT_OK, new Intent().putExtra(MainActivity.OPEN_FILTER, new GtasksFilter(gtasksList)));
finish();
return Unit.INSTANCE;
}
private void onListDeleted(boolean deleted) {
@ -225,7 +227,7 @@ public class GoogleTaskListSettingsActivity extends BaseListSettingsActivity {
}
}
private void onListRenamed(TaskList taskList) {
private Unit onListRenamed(TaskList taskList) {
gtasksList.setTitle(taskList.getTitle());
gtasksList.setColor(selectedColor);
gtasksList.setIcon(selectedIcon);
@ -235,11 +237,13 @@ public class GoogleTaskListSettingsActivity extends BaseListSettingsActivity {
new Intent(TaskListFragment.ACTION_RELOAD)
.putExtra(MainActivity.OPEN_FILTER, new GtasksFilter(gtasksList)));
finish();
return Unit.INSTANCE;
}
private void requestFailed(Throwable error) {
private Unit requestFailed(Throwable error) {
Timber.e(error);
hideProgressIndicator();
Toast.makeText(this, R.string.gtasks_GLA_errorIOAuth, Toast.LENGTH_LONG).show();
return Unit.INSTANCE;
}
}

@ -1,13 +0,0 @@
package org.tasks.activities;
import com.google.api.services.tasks.model.TaskList;
import com.todoroo.astrid.gtasks.api.GtasksInvoker;
import org.tasks.data.GoogleTaskList;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class RenameListViewModel extends CompletableViewModel<TaskList> {
void renameList(GtasksInvoker invoker, GoogleTaskList list, String name) {
run(() -> invoker.forAccount(list.getAccount()).renameGtaskList(list.getRemoteId(), name));
}
}

@ -0,0 +1,12 @@
package org.tasks.activities
import com.google.api.services.tasks.model.TaskList
import com.todoroo.astrid.gtasks.api.GtasksInvoker
import org.tasks.data.GoogleTaskList
import org.tasks.ui.CompletableViewModel
class RenameListViewModel : CompletableViewModel<TaskList?>() {
fun renameList(invoker: GtasksInvoker, list: GoogleTaskList, name: String?) {
run { invoker.forAccount(list.account!!).renameGtaskList(list.remoteId, name) }
}
}

@ -1,11 +0,0 @@
package org.tasks.caldav;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class AddCaldavAccountViewModel extends CompletableViewModel<String> {
void addAccount(CaldavClient client, String url, String username, String password) {
run(
() -> client.setForeground().forUrl(url, username, password).getHomeSet());
}
}

@ -0,0 +1,9 @@
package org.tasks.caldav
import org.tasks.ui.CompletableViewModel
class AddCaldavAccountViewModel : CompletableViewModel<String>() {
fun addAccount(client: CaldavClient, url: String?, username: String?, password: String?) {
run { client.setForeground().forUrl(url, username, password).homeSet }
}
}

@ -22,6 +22,7 @@ import com.todoroo.astrid.helper.UUIDHelper;
import com.todoroo.astrid.service.TaskDeleter;
import java.net.ConnectException;
import javax.inject.Inject;
import kotlin.Unit;
import org.tasks.R;
import org.tasks.activities.BaseListSettingsActivity;
import org.tasks.data.CaldavAccount;
@ -152,7 +153,7 @@ public abstract class BaseCaldavCalendarSettingsActivity extends BaseListSetting
return progressView.getVisibility() == View.VISIBLE;
}
protected void requestFailed(Throwable t) {
protected Unit requestFailed(Throwable t) {
hideProgressIndicator();
if (t instanceof HttpException) {
@ -164,6 +165,7 @@ public abstract class BaseCaldavCalendarSettingsActivity extends BaseListSetting
} else {
showSnackbar(R.string.error_adding_account, t.getMessage());
}
return Unit.INSTANCE;
}
private void showSnackbar(int resId, Object... formatArgs) {
@ -181,7 +183,7 @@ public abstract class BaseCaldavCalendarSettingsActivity extends BaseListSetting
snackbar.show();
}
protected void createSuccessful(String url) {
protected Unit createSuccessful(String url) {
CaldavCalendar caldavCalendar = new CaldavCalendar();
caldavCalendar.setUuid(UUIDHelper.newUUID());
caldavCalendar.setAccount(caldavAccount.getUuid());
@ -194,9 +196,10 @@ public abstract class BaseCaldavCalendarSettingsActivity extends BaseListSetting
RESULT_OK,
new Intent().putExtra(MainActivity.OPEN_FILTER, new CaldavFilter(caldavCalendar)));
finish();
return Unit.INSTANCE;
}
protected void updateCalendar() {
protected Unit updateCalendar() {
caldavCalendar.setName(getNewName());
caldavCalendar.setColor(selectedColor);
caldavCalendar.setIcon(selectedIcon);
@ -206,6 +209,7 @@ public abstract class BaseCaldavCalendarSettingsActivity extends BaseListSetting
new Intent(TaskListFragment.ACTION_RELOAD)
.putExtra(MainActivity.OPEN_FILTER, new CaldavFilter(caldavCalendar)));
finish();
return Unit.INSTANCE;
}
@Override

@ -2,9 +2,8 @@ package org.tasks.caldav
import android.app.Activity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.todoroo.astrid.helper.UUIDHelper
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.R
@ -16,16 +15,13 @@ import javax.inject.Inject
class CaldavAccountSettingsActivity : BaseCaldavAccountSettingsActivity(), Toolbar.OnMenuItemClickListener {
@Inject lateinit var client: CaldavClient
private var addCaldavAccountViewModel: AddCaldavAccountViewModel? = null
private var updateCaldavAccountViewModel: UpdateCaldavAccountViewModel? = null
private val addCaldavAccountViewModel: AddCaldavAccountViewModel by viewModels()
private val updateCaldavAccountViewModel: UpdateCaldavAccountViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val provider = ViewModelProvider(this)
addCaldavAccountViewModel = provider.get(AddCaldavAccountViewModel::class.java)
updateCaldavAccountViewModel = provider.get(UpdateCaldavAccountViewModel::class.java)
addCaldavAccountViewModel!!.observe(this, Observer { principal: String -> this.addAccount(principal) }, Observer { t: Throwable? -> requestFailed(t!!) })
updateCaldavAccountViewModel!!.observe(this, Observer { principal: String? -> this.updateAccount(principal) }, Observer { t: Throwable? -> requestFailed(t!!) })
addCaldavAccountViewModel.observe(this, { addAccount(it) }, { requestFailed(it) })
updateCaldavAccountViewModel.observe(this, { updateAccount(it) }, { requestFailed(it) })
}
override val description: Int
@ -61,11 +57,11 @@ class CaldavAccountSettingsActivity : BaseCaldavAccountSettingsActivity(), Toolb
}
override fun addAccount(url: String?, username: String?, password: String?) {
addCaldavAccountViewModel!!.addAccount(client, url, username, password)
addCaldavAccountViewModel.addAccount(client, url, username, password)
}
override fun updateAccount(url: String?, username: String?, password: String?) {
updateCaldavAccountViewModel!!.updateCaldavAccount(client, url, username, password)
updateCaldavAccountViewModel.updateCaldavAccount(client, url, username, password)
}
override fun updateAccount() {

@ -1,11 +0,0 @@
package org.tasks.caldav;
import org.tasks.data.CaldavAccount;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class CreateCalendarViewModel extends CompletableViewModel<String> {
void createCalendar(CaldavClient client, CaldavAccount account, String name, int color) {
run(() -> client.forAccount(account).makeCollection(name, color));
}
}

@ -0,0 +1,10 @@
package org.tasks.caldav
import org.tasks.data.CaldavAccount
import org.tasks.ui.CompletableViewModel
class CreateCalendarViewModel : CompletableViewModel<String?>() {
fun createCalendar(client: CaldavClient, account: CaldavAccount?, name: String?, color: Int) {
run { client.forAccount(account).makeCollection(name, color) }
}
}

@ -1,11 +0,0 @@
package org.tasks.caldav;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class UpdateCaldavAccountViewModel extends CompletableViewModel<String> {
void updateCaldavAccount(
CaldavClient client, String url, String username, String password) {
run(() -> client.forUrl(url, username, password).getHomeSet());
}
}

@ -0,0 +1,12 @@
package org.tasks.caldav
import org.tasks.ui.CompletableViewModel
class UpdateCaldavAccountViewModel : CompletableViewModel<String>() {
fun updateCaldavAccount(
client: CaldavClient, url: String?, username: String?, password: String?) {
run {
client.forUrl(url, username, password).homeSet
}
}
}

@ -1,13 +0,0 @@
package org.tasks.caldav;
import org.tasks.data.CaldavAccount;
import org.tasks.data.CaldavCalendar;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class UpdateCalendarViewModel extends CompletableViewModel<String> {
void updateCalendar(
CaldavClient client, CaldavAccount account, CaldavCalendar calendar, String name, int color) {
run(() -> client.forCalendar(account, calendar).updateCollection(name, color));
}
}

@ -0,0 +1,12 @@
package org.tasks.caldav
import org.tasks.data.CaldavAccount
import org.tasks.data.CaldavCalendar
import org.tasks.ui.CompletableViewModel
class UpdateCalendarViewModel : CompletableViewModel<String?>() {
fun updateCalendar(
client: CaldavClient, account: CaldavAccount?, calendar: CaldavCalendar?, name: String?, color: Int) {
run { client.forCalendar(account, calendar).updateCollection(name, color) }
}
}

@ -1,17 +0,0 @@
package org.tasks.etesync;
import androidx.core.util.Pair;
import com.etesync.journalmanager.UserInfoManager.UserInfo;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class AddEteSyncAccountViewModel extends CompletableViewModel<Pair<UserInfo, String>> {
void addAccount(EteSyncClient client, String url, String username, String password) {
run(
() -> {
client.setForeground();
String token = client.forUrl(url, username, null, null).getToken(password);
return Pair.create(client.forUrl(url, username, null, token).getUserInfo(), token);
});
}
}

@ -0,0 +1,15 @@
package org.tasks.etesync
import androidx.core.util.Pair
import com.etesync.journalmanager.UserInfoManager
import org.tasks.ui.CompletableViewModel
class AddEteSyncAccountViewModel : CompletableViewModel<Pair<UserInfoManager.UserInfo, String>>() {
fun addAccount(client: EteSyncClient, url: String?, username: String?, password: String?) {
run {
client.setForeground()
val token = client.forUrl(url, username, null, null).getToken(password)
Pair.create(client.forUrl(url, username, null, token!!).userInfo, token)
}
}
}

@ -1,11 +0,0 @@
package org.tasks.etesync;
import org.tasks.data.CaldavAccount;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class CreateCalendarViewModel extends CompletableViewModel<String> {
void createCalendar(EteSyncClient client, CaldavAccount account, String name, int color) {
run(() -> client.forAccount(account).makeCollection(name, color));
}
}

@ -0,0 +1,10 @@
package org.tasks.etesync
import org.tasks.data.CaldavAccount
import org.tasks.ui.CompletableViewModel
class CreateCalendarViewModel : CompletableViewModel<String?>() {
fun createCalendar(client: EteSyncClient, account: CaldavAccount?, name: String?, color: Int) {
run { client.forAccount(account!!).makeCollection(name, color) }
}
}

@ -1,15 +0,0 @@
package org.tasks.etesync;
import org.tasks.data.CaldavAccount;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class CreateUserInfoViewModel extends CompletableViewModel<String> {
void createUserInfo(EteSyncClient client, CaldavAccount caldavAccount, String derivedKey) {
run(() -> {
client.forAccount(caldavAccount).createUserInfo(derivedKey);
return derivedKey;
});
}
}

@ -0,0 +1,13 @@
package org.tasks.etesync
import org.tasks.data.CaldavAccount
import org.tasks.ui.CompletableViewModel
class CreateUserInfoViewModel : CompletableViewModel<String?>() {
fun createUserInfo(client: EteSyncClient, caldavAccount: CaldavAccount?, derivedKey: String?) {
run {
client.forAccount(caldavAccount!!).createUserInfo(derivedKey)
derivedKey
}
}
}

@ -23,6 +23,7 @@ import com.google.android.material.snackbar.Snackbar;
import dagger.hilt.android.AndroidEntryPoint;
import java.net.ConnectException;
import javax.inject.Inject;
import kotlin.Unit;
import org.tasks.R;
import org.tasks.data.CaldavAccount;
import org.tasks.databinding.ActivityEtesyncEncryptionSettingsBinding;
@ -95,13 +96,14 @@ public class EncryptionSettingsActivity extends ThemedInjectingAppCompatActivity
return binding.progressBar.progressBar.getVisibility() == View.VISIBLE;
}
private void returnDerivedKey(String derivedKey) {
private Unit returnDerivedKey(String derivedKey) {
hideProgressIndicator();
Intent result = new Intent();
result.putExtra(EXTRA_DERIVED_KEY, derivedKey);
setResult(RESULT_OK, result);
finish();
return Unit.INSTANCE;
}
private void save() {
@ -151,7 +153,7 @@ public class EncryptionSettingsActivity extends ThemedInjectingAppCompatActivity
}
}
protected void requestFailed(Throwable t) {
protected Unit requestFailed(Throwable t) {
hideProgressIndicator();
if (t instanceof HttpException) {
@ -164,6 +166,7 @@ public class EncryptionSettingsActivity extends ThemedInjectingAppCompatActivity
Timber.e(t);
showSnackbar(R.string.error_adding_account, t.getMessage());
}
return Unit.INSTANCE;
}
private void showSnackbar(int resId, Object... formatArgs) {

@ -4,10 +4,9 @@ import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.widget.Toolbar
import androidx.core.util.Pair
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import butterknife.OnCheckedChanged
import com.etesync.journalmanager.Crypto.CryptoManager
import com.etesync.journalmanager.Exceptions.IntegrityException
@ -29,31 +28,28 @@ import javax.inject.Inject
class EteSyncAccountSettingsActivity : BaseCaldavAccountSettingsActivity(), Toolbar.OnMenuItemClickListener {
@Inject lateinit var eteSyncClient: EteSyncClient
private var addAccountViewModel: AddEteSyncAccountViewModel? = null
private var updateAccountViewModel: UpdateEteSyncAccountViewModel? = null
private val addAccountViewModel: AddEteSyncAccountViewModel by viewModels()
private val updateAccountViewModel: UpdateEteSyncAccountViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding!!.repeat.visibility = View.GONE
binding!!.showAdvanced.visibility = View.VISIBLE
updateUrlVisibility()
val provider = ViewModelProvider(this)
addAccountViewModel = provider.get(AddEteSyncAccountViewModel::class.java)
updateAccountViewModel = provider.get(UpdateEteSyncAccountViewModel::class.java)
}
override fun onResume() {
super.onResume()
if (!isFinishing) {
addAccountViewModel!!.observe(this, Observer { userInfoAndToken: Pair<UserInfoManager.UserInfo, String> -> this.addAccount(userInfoAndToken) }, Observer { t: Throwable? -> requestFailed(t!!) })
updateAccountViewModel!!.observe(this, Observer { userInfoAndToken: Pair<UserInfoManager.UserInfo, String> -> this.updateAccount(userInfoAndToken) }, Observer { t: Throwable? -> requestFailed(t!!) })
addAccountViewModel.observe(this, { addAccount(it) }, { requestFailed(it) })
updateAccountViewModel.observe(this, { updateAccount(it) }, { requestFailed(it) })
}
}
override fun onPause() {
super.onPause()
addAccountViewModel!!.removeObserver(this)
updateAccountViewModel!!.removeObserver(this)
addAccountViewModel.removeObserver(this)
updateAccountViewModel.removeObserver(this)
}
override val description: Int
@ -121,11 +117,11 @@ class EteSyncAccountSettingsActivity : BaseCaldavAccountSettingsActivity(), Tool
}
override fun addAccount(url: String?, username: String?, password: String?) {
addAccountViewModel!!.addAccount(eteSyncClient, url, username, password)
addAccountViewModel.addAccount(eteSyncClient, url, username, password)
}
override fun updateAccount(url: String?, username: String?, password: String?) {
updateAccountViewModel!!.updateAccount(
updateAccountViewModel.updateAccount(
eteSyncClient,
url,
username,

@ -74,8 +74,8 @@ class EteSyncClient {
interceptor: DebugNetworkInterceptor,
url: String?,
username: String?,
encryptionPassword: String,
token: String,
encryptionPassword: String?,
token: String?,
foreground: Boolean) {
this.context = context
this.encryption = encryption
@ -119,7 +119,7 @@ class EteSyncClient {
}
@Throws(KeyManagementException::class, NoSuchAlgorithmException::class)
fun forUrl(url: String?, username: String?, encryptionPassword: String, token: String): EteSyncClient {
fun forUrl(url: String?, username: String?, encryptionPassword: String?, token: String?): EteSyncClient {
return EteSyncClient(
context,
encryption,

@ -1,17 +0,0 @@
package org.tasks.etesync;
import org.tasks.data.CaldavAccount;
import org.tasks.data.CaldavCalendar;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class UpdateCalendarViewModel extends CompletableViewModel<String> {
void updateCalendar(
EteSyncClient client,
CaldavAccount account,
CaldavCalendar calendar,
String name,
int color) {
run(() -> client.forAccount(account).updateCollection(calendar, name, color));
}
}

@ -0,0 +1,16 @@
package org.tasks.etesync
import org.tasks.data.CaldavAccount
import org.tasks.data.CaldavCalendar
import org.tasks.ui.CompletableViewModel
class UpdateCalendarViewModel : CompletableViewModel<String?>() {
fun updateCalendar(
client: EteSyncClient,
account: CaldavAccount?,
calendar: CaldavCalendar?,
name: String?,
color: Int) {
run { client.forAccount(account!!).updateCollection(calendar!!, name, color) }
}
}

@ -1,30 +0,0 @@
package org.tasks.etesync;
import static org.tasks.Strings.isNullOrEmpty;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import com.etesync.journalmanager.UserInfoManager.UserInfo;
import org.tasks.ui.CompletableViewModel;
@SuppressWarnings("WeakerAccess")
public class UpdateEteSyncAccountViewModel extends CompletableViewModel<Pair<UserInfo, String>> {
void updateAccount(
EteSyncClient client,
String url,
String username,
@Nullable String password,
@Nullable String token) {
run(
() -> {
client.setForeground();
if (isNullOrEmpty(password)) {
return Pair.create(client.forUrl(url, username, null, token).getUserInfo(), token);
} else {
String newToken = client.forUrl(url, username, null, null).getToken(password);
return Pair.create(
client.forUrl(url, username, null, newToken).getUserInfo(), newToken);
}
});
}
}

@ -0,0 +1,21 @@
package org.tasks.etesync
import androidx.core.util.Pair
import com.etesync.journalmanager.UserInfoManager
import org.tasks.Strings.isNullOrEmpty
import org.tasks.ui.CompletableViewModel
class UpdateEteSyncAccountViewModel : CompletableViewModel<Pair<UserInfoManager.UserInfo, String>>() {
fun updateAccount(
client: EteSyncClient, url: String?, user: String?, pass: String?, token: String?) {
run {
client.setForeground()
if (isNullOrEmpty(pass)) {
Pair.create(client.forUrl(url, user, null, token).userInfo, token)
} else {
val newToken = client.forUrl(url, user, null, null).getToken(pass)
Pair.create(client.forUrl(url, user, null, newToken).userInfo, newToken)
}
}
}
}

@ -16,6 +16,7 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.tasks.R
import org.tasks.Strings.isNullOrEmpty
import org.tasks.caldav.BaseCaldavAccountSettingsActivity
import org.tasks.caldav.CaldavAccountSettingsActivity
import org.tasks.data.CaldavAccount
import org.tasks.data.CaldavAccount.Companion.TYPE_LOCAL
@ -168,7 +169,7 @@ class Synchronization : InjectingPreferenceFragment() {
if (account.isCaldavAccount) CaldavAccountSettingsActivity::class.java
else EteSyncAccountSettingsActivity::class.java
)
intent.putExtra(CaldavAccountSettingsActivity.EXTRA_CALDAV_DATA, account)
intent.putExtra(BaseCaldavAccountSettingsActivity.EXTRA_CALDAV_DATA, account)
startActivityForResult(intent, REQUEST_CALDAV_SETTINGS)
false
}

@ -1,58 +0,0 @@
package org.tasks.ui;
import static com.todoroo.andlib.utility.AndroidUtilities.assertMainThread;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.Callable;
public abstract class CompletableViewModel<T> extends ViewModel {
private final MutableLiveData<T> data = new MutableLiveData<>();
private final MutableLiveData<Throwable> error = new MutableLiveData<>();
private final CompositeDisposable disposables = new CompositeDisposable();
private boolean inProgress;
public void observe(
LifecycleOwner lifecycleOwner, Observer<T> dataObserver, Observer<Throwable> errorObserver) {
data.observe(lifecycleOwner, dataObserver);
error.observe(lifecycleOwner, errorObserver);
}
public boolean inProgress() {
return inProgress;
}
protected void run(Callable<T> callable) {
assertMainThread();
if (!inProgress) {
inProgress = true;
disposables.add(
Single.fromCallable(callable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doFinally(
() -> {
assertMainThread();
inProgress = false;
})
.subscribe(data::setValue, error::setValue));
}
}
@Override
protected void onCleared() {
disposables.dispose();
}
public void removeObserver(LifecycleOwner owner) {
data.removeObservers(owner);
error.removeObservers(owner);
}
}

@ -0,0 +1,55 @@
package org.tasks.ui
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.observe
import com.todoroo.andlib.utility.AndroidUtilities
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
abstract class CompletableViewModel<T> : ViewModel() {
private val data = MutableLiveData<T>()
private val error = MutableLiveData<Throwable>()
private val disposables = CompositeDisposable()
private var inProgress = false
fun observe(
lifecycleOwner: LifecycleOwner,
dataObserver: (T) -> Unit,
errorObserver: (Throwable) -> Unit) {
data.observe(lifecycleOwner, dataObserver)
error.observe(lifecycleOwner, errorObserver)
}
fun inProgress(): Boolean {
return inProgress
}
protected fun run(callable: () -> T) {
AndroidUtilities.assertMainThread()
if (!inProgress) {
inProgress = true
disposables.add(
Single.fromCallable(callable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doFinally {
AndroidUtilities.assertMainThread()
inProgress = false
}
.subscribe({ value: T -> data.setValue(value) }) { value: Throwable -> error.setValue(value) })
}
}
override fun onCleared() {
disposables.dispose()
}
fun removeObserver(owner: LifecycleOwner) {
data.removeObservers(owner)
error.removeObservers(owner)
}
}
Loading…
Cancel
Save