replace kotlin-result-calladapter with networkresult-calladapter (#2569)

* replace kotlin-result-calladapter with networkresult-calladapter

* fix tests
This commit is contained in:
Konrad Pozniak 2022-05-30 20:03:40 +02:00 committed by GitHub
parent 131309e99c
commit e1c8461423
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 53 additions and 62 deletions

View file

@ -141,7 +141,7 @@ dependencies {
implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
implementation "com.squareup.retrofit2:adapter-rxjava3:$retrofitVersion"
implementation "at.connyduck:kotlin-result-calladapter:1.0.1"
implementation "at.connyduck:networkresult-calladapter:1.0.0"
implementation "com.squareup.okhttp3:okhttp:$okhttpVersion"
implementation "com.squareup.okhttp3:logging-interceptor:$okhttpVersion"

View file

@ -40,6 +40,7 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import androidx.viewpager2.widget.MarginPageTransformer
import at.connyduck.calladapter.networkresult.fold
import autodispose2.androidx.lifecycle.autoDispose
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager

View file

@ -31,6 +31,7 @@ import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.transition.TransitionManager
import at.connyduck.calladapter.networkresult.fold
import at.connyduck.sparkbutton.helpers.Utils
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider.from
import autodispose2.autoDispose

View file

@ -20,6 +20,7 @@ import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import at.connyduck.calladapter.networkresult.fold
import com.keylesspalace.tusky.appstore.AnnouncementReadEvent
import com.keylesspalace.tusky.appstore.EventHub
import com.keylesspalace.tusky.components.instanceinfo.InstanceInfoRepository

View file

@ -23,6 +23,7 @@ import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import at.connyduck.calladapter.networkresult.fold
import com.keylesspalace.tusky.components.compose.ComposeActivity.QueuedMedia
import com.keylesspalace.tusky.components.compose.ComposeAutoCompleteAdapter.AutocompleteResult
import com.keylesspalace.tusky.components.drafts.DraftHelper
@ -39,7 +40,6 @@ import com.keylesspalace.tusky.service.ServiceClient
import com.keylesspalace.tusky.service.StatusToSend
import com.keylesspalace.tusky.util.combineLiveData
import com.keylesspalace.tusky.util.randomAlphanumericString
import com.keylesspalace.tusky.util.result
import com.keylesspalace.tusky.util.toLiveData
import io.reactivex.rxjava3.core.Observable
import kotlinx.coroutines.Dispatchers
@ -351,8 +351,7 @@ class ComposeViewModel @Inject constructor(
fun searchAutocompleteSuggestions(token: String): List<AutocompleteResult> {
when (token[0]) {
'@' -> {
return api.searchAccountsCall(query = token.substring(1), limit = 10)
.result()
return api.searchAccountsSync(query = token.substring(1), limit = 10)
.fold({ accounts ->
accounts.map { AutocompleteResult.AccountResult(it) }
}, { e ->
@ -361,8 +360,7 @@ class ComposeViewModel @Inject constructor(
})
}
'#' -> {
return api.searchCall(query = token, type = SearchType.Hashtag.apiParameter, limit = 10)
.result()
return api.searchSync(query = token, type = SearchType.Hashtag.apiParameter, limit = 10)
.fold({ searchResult ->
searchResult.hashtags.map { AutocompleteResult.HashtagResult(it.name) }
}, { e ->

View file

@ -16,6 +16,9 @@
package com.keylesspalace.tusky.components.instanceinfo
import android.util.Log
import at.connyduck.calladapter.networkresult.fold
import at.connyduck.calladapter.networkresult.getOrElse
import at.connyduck.calladapter.networkresult.onSuccess
import com.keylesspalace.tusky.db.AccountManager
import com.keylesspalace.tusky.db.AppDatabase
import com.keylesspalace.tusky.db.EmojisEntity

View file

@ -26,6 +26,7 @@ import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
import androidx.lifecycle.lifecycleScope
import at.connyduck.calladapter.networkresult.fold
import com.bumptech.glide.Glide
import com.keylesspalace.tusky.BaseActivity
import com.keylesspalace.tusky.BuildConfig

View file

@ -23,6 +23,8 @@ import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.preference.PreferenceManager
import at.connyduck.calladapter.networkresult.onFailure
import at.connyduck.calladapter.networkresult.onSuccess
import com.google.android.material.snackbar.Snackbar
import com.keylesspalace.tusky.R
import com.keylesspalace.tusky.components.login.LoginActivity

View file

@ -21,6 +21,7 @@ import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import at.connyduck.calladapter.networkresult.fold
import com.keylesspalace.tusky.appstore.EventHub
import com.keylesspalace.tusky.entity.ScheduledStatus
import com.keylesspalace.tusky.network.MastodonApi

View file

@ -18,7 +18,7 @@ package com.keylesspalace.tusky.di
import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import at.connyduck.calladapter.kotlinresult.KotlinResultCallAdapterFactory
import at.connyduck.calladapter.networkresult.NetworkResultCallAdapterFactory
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.keylesspalace.tusky.BuildConfig
@ -111,7 +111,7 @@ class NetworkModule {
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.addCallAdapterFactory(KotlinResultCallAdapterFactory.create())
.addCallAdapterFactory(NetworkResultCallAdapterFactory.create())
.build()
}

View file

@ -15,6 +15,7 @@
package com.keylesspalace.tusky.network
import at.connyduck.calladapter.networkresult.NetworkResult
import com.keylesspalace.tusky.entity.AccessToken
import com.keylesspalace.tusky.entity.Account
import com.keylesspalace.tusky.entity.Announcement
@ -74,10 +75,10 @@ interface MastodonApi {
}
@GET("/api/v1/custom_emojis")
suspend fun getCustomEmojis(): Result<List<Emoji>>
suspend fun getCustomEmojis(): NetworkResult<List<Emoji>>
@GET("api/v1/instance")
suspend fun getInstance(): Result<Instance>
suspend fun getInstance(): NetworkResult<Instance>
@GET("api/v1/filters")
fun getFilters(): Single<List<Filter>>
@ -145,7 +146,7 @@ interface MastodonApi {
suspend fun updateMedia(
@Path("mediaId") mediaId: String,
@Field("description") description: String
): Result<Attachment>
): NetworkResult<Attachment>
@GET("api/v1/media/{mediaId}")
suspend fun getMedia(
@ -158,7 +159,7 @@ interface MastodonApi {
@Header(DOMAIN_HEADER) domain: String,
@Header("Idempotency-Key") idempotencyKey: String,
@Body status: NewStatus
): Result<Status>
): NetworkResult<Status>
@GET("api/v1/statuses/{id}")
fun status(
@ -246,10 +247,10 @@ interface MastodonApi {
@DELETE("api/v1/scheduled_statuses/{id}")
suspend fun deleteScheduledStatus(
@Path("id") scheduledStatusId: String
): Result<ResponseBody>
): NetworkResult<ResponseBody>
@GET("api/v1/accounts/verify_credentials")
suspend fun accountVerifyCredentials(): Result<Account>
suspend fun accountVerifyCredentials(): NetworkResult<Account>
@FormUrlEncoded
@PATCH("api/v1/accounts/update_credentials")
@ -274,7 +275,7 @@ interface MastodonApi {
@Part(value = "fields_attributes[2][value]") fieldValue2: RequestBody?,
@Part(value = "fields_attributes[3][name]") fieldName3: RequestBody?,
@Part(value = "fields_attributes[3][value]") fieldValue3: RequestBody?
): Result<Account>
): NetworkResult<Account>
@GET("api/v1/accounts/search")
suspend fun searchAccounts(
@ -282,15 +283,15 @@ interface MastodonApi {
@Query("resolve") resolve: Boolean? = null,
@Query("limit") limit: Int? = null,
@Query("following") following: Boolean? = null
): Result<List<TimelineAccount>>
): NetworkResult<List<TimelineAccount>>
@GET("api/v1/accounts/search")
fun searchAccountsCall(
fun searchAccountsSync(
@Query("q") query: String,
@Query("resolve") resolve: Boolean? = null,
@Query("limit") limit: Int? = null,
@Query("following") following: Boolean? = null
): Call<List<TimelineAccount>>
): NetworkResult<List<TimelineAccount>>
@GET("api/v1/accounts/{id}")
fun account(
@ -445,7 +446,7 @@ interface MastodonApi {
@Field("redirect_uris") redirectUris: String,
@Field("scopes") scopes: String,
@Field("website") website: String
): Result<AppCredentials>
): NetworkResult<AppCredentials>
@FormUrlEncoded
@POST("oauth/token")
@ -456,34 +457,34 @@ interface MastodonApi {
@Field("redirect_uri") redirectUri: String,
@Field("code") code: String,
@Field("grant_type") grantType: String
): Result<AccessToken>
): NetworkResult<AccessToken>
@GET("/api/v1/lists")
suspend fun getLists(): Result<List<MastoList>>
suspend fun getLists(): NetworkResult<List<MastoList>>
@FormUrlEncoded
@POST("api/v1/lists")
suspend fun createList(
@Field("title") title: String
): Result<MastoList>
): NetworkResult<MastoList>
@FormUrlEncoded
@PUT("api/v1/lists/{listId}")
suspend fun updateList(
@Path("listId") listId: String,
@Field("title") title: String
): Result<MastoList>
): NetworkResult<MastoList>
@DELETE("api/v1/lists/{listId}")
suspend fun deleteList(
@Path("listId") listId: String
): Result<Unit>
): NetworkResult<Unit>
@GET("api/v1/lists/{listId}/accounts")
suspend fun getAccountsInList(
@Path("listId") listId: String,
@Query("limit") limit: Int
): Result<List<TimelineAccount>>
): NetworkResult<List<TimelineAccount>>
@FormUrlEncoded
// @DELETE doesn't support fields
@ -491,14 +492,14 @@ interface MastodonApi {
suspend fun deleteAccountFromList(
@Path("listId") listId: String,
@Field("account_ids[]") accountIds: List<String>
): Result<Unit>
): NetworkResult<Unit>
@FormUrlEncoded
@POST("api/v1/lists/{listId}/accounts")
suspend fun addAccountToList(
@Path("listId") listId: String,
@Field("account_ids[]") accountIds: List<String>
): Result<Unit>
): NetworkResult<Unit>
@GET("/api/v1/conversations")
suspend fun getConversations(
@ -547,24 +548,24 @@ interface MastodonApi {
@GET("api/v1/announcements")
suspend fun listAnnouncements(
@Query("with_dismissed") withDismissed: Boolean = true
): Result<List<Announcement>>
): NetworkResult<List<Announcement>>
@POST("api/v1/announcements/{id}/dismiss")
suspend fun dismissAnnouncement(
@Path("id") announcementId: String
): Result<ResponseBody>
): NetworkResult<ResponseBody>
@PUT("api/v1/announcements/{id}/reactions/{name}")
suspend fun addAnnouncementReaction(
@Path("id") announcementId: String,
@Path("name") name: String
): Result<ResponseBody>
): NetworkResult<ResponseBody>
@DELETE("api/v1/announcements/{id}/reactions/{name}")
suspend fun removeAnnouncementReaction(
@Path("id") announcementId: String,
@Path("name") name: String
): Result<ResponseBody>
): NetworkResult<ResponseBody>
@FormUrlEncoded
@POST("api/v1/reports")
@ -601,14 +602,14 @@ interface MastodonApi {
): Single<SearchResult>
@GET("api/v2/search")
fun searchCall(
fun searchSync(
@Query("q") query: String?,
@Query("type") type: String? = null,
@Query("resolve") resolve: Boolean? = null,
@Query("limit") limit: Int? = null,
@Query("offset") offset: Int? = null,
@Query("following") following: Boolean? = null
): Call<SearchResult>
): NetworkResult<SearchResult>
@FormUrlEncoded
@POST("api/v1/accounts/{id}/note")
@ -629,7 +630,7 @@ interface MastodonApi {
// Should be generated dynamically from all the available notification
// types defined in [com.keylesspalace.tusky.entities.Notification.Types]
@FieldMap data: Map<String, Boolean>
): Result<NotificationSubscribeResult>
): NetworkResult<NotificationSubscribeResult>
@FormUrlEncoded
@PUT("api/v1/push/subscription")
@ -637,11 +638,11 @@ interface MastodonApi {
@Header("Authorization") auth: String,
@Header(DOMAIN_HEADER) domain: String,
@FieldMap data: Map<String, Boolean>
): Result<NotificationSubscribeResult>
): NetworkResult<NotificationSubscribeResult>
@DELETE("api/v1/push/subscription")
suspend fun unsubscribePushNotifications(
@Header("Authorization") auth: String,
@Header(DOMAIN_HEADER) domain: String,
): Result<ResponseBody>
): NetworkResult<ResponseBody>
}

View file

@ -15,6 +15,7 @@ import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import at.connyduck.calladapter.networkresult.fold
import com.keylesspalace.tusky.R
import com.keylesspalace.tusky.appstore.EventHub
import com.keylesspalace.tusky.appstore.StatusComposedEvent

View file

@ -1,23 +0,0 @@
package com.keylesspalace.tusky.util
import retrofit2.Call
import retrofit2.HttpException
/**
* Synchronously executes the call and returns the response encapsulated in a kotlin.Result.
* Since Result is an inline class it is not possible to do this with a Retrofit adapter unfortunately.
* More efficient then calling a suspending method with runBlocking
*/
fun <T> Call<T>.result(): Result<T> {
return try {
val response = execute()
val responseBody = response.body()
if (response.isSuccessful && responseBody != null) {
Result.success(responseBody)
} else {
Result.failure(HttpException(response))
}
} catch (e: Exception) {
Result.failure(e)
}
}

View file

@ -19,6 +19,7 @@ package com.keylesspalace.tusky.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import at.connyduck.calladapter.networkresult.fold
import com.keylesspalace.tusky.entity.TimelineAccount
import com.keylesspalace.tusky.network.MastodonApi
import com.keylesspalace.tusky.util.Either

View file

@ -21,6 +21,7 @@ import androidx.core.net.toUri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import at.connyduck.calladapter.networkresult.fold
import com.keylesspalace.tusky.appstore.EventHub
import com.keylesspalace.tusky.appstore.ProfileEditedEvent
import com.keylesspalace.tusky.entity.Account

View file

@ -18,6 +18,7 @@ package com.keylesspalace.tusky.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import at.connyduck.calladapter.networkresult.fold
import com.keylesspalace.tusky.entity.MastoList
import com.keylesspalace.tusky.network.MastodonApi
import com.keylesspalace.tusky.util.replacedFirstWhich

View file

@ -19,6 +19,7 @@ import android.content.Intent
import android.os.Looper.getMainLooper
import android.widget.EditText
import androidx.test.ext.junit.runners.AndroidJUnit4
import at.connyduck.calladapter.networkresult.NetworkResult
import com.keylesspalace.tusky.components.compose.ComposeActivity
import com.keylesspalace.tusky.components.compose.ComposeViewModel
import com.keylesspalace.tusky.components.instanceinfo.InstanceInfoRepository
@ -95,12 +96,12 @@ class ComposeActivityTest {
}
apiMock = mock {
onBlocking { getCustomEmojis() } doReturn Result.success(emptyList())
onBlocking { getCustomEmojis() } doReturn NetworkResult.success(emptyList())
onBlocking { getInstance() } doReturn instanceResponseCallback?.invoke().let { instance ->
if (instance == null) {
Result.failure(Throwable())
NetworkResult.failure(Throwable())
} else {
Result.success(instance)
NetworkResult.success(instance)
}
}
}