Einar  Hintz

Einar Hintz

1593396615

Kotlin sealed class for success and error handling

A well-known Use-case

Sealed class is not new in other programming languages such as C# and Scala. The sealed class provides a way to organize our code to look a lot nicer and easy to work with.

/* Copyright 2020 Seanghay Yath.	
	   SPDX-License-Identifier: Apache-2.0 */

	@WorkerThread
	suspend fun fetchPosts() {
	  val response = httpClient.posts()

	  withContext(Dispatchers.Main) {
	    when (response) {
	      is ResultOf.Success -> {
	        // destructing data object
	        val (posts) = response

	        // update the view
	        adapter.submitList(posts)
	      } 

	      is ResultOf.Failure -> {
	        val (message, throwable) = response;
	        handlePostsFailure(messsage, throwable)

	        // log error message to logcat
	        Timber.e(throwable, message)
	      }
	    }
	  }
	}

An example of how to use Sealed class for handling error and success

As you can see in the example above that there is no need to manually cast objects. Kotlin compiler knows what data type it should be.

Sealed classes work well with LiveData and ViewModels

Oftentimes, we use LiveData to store data from APIs or databases, however, data from those I/O operations could cause failure, so the best way to handle those errors and successful responses is to use Sealed classes.

/* Copyright 2020 Seanghay Yath (@seanghay)
	   SPDX-License-Identifier: Apache-2.0 */

	sealed class ResultOf<out T> {
	  data class Success<out R>(val value: R): ResultOf<R>()
	  data class Failure(
	     val message: String?, 
	     val throwable: Throwable?
	  ): ResultOf<Nothing>()
	}

In our ViewModels, it would look something similar to this. I assume that you all familiar with Kotlin Coroutines.

/* Copyright 2020 Seanghay Yath (@seanghay)
	   SPDX-License-Identifier: Apache-2.0 */

	class PostViewModel: ViewModel() {

	   // Retrofit service
	   private val postService: PostService = HttpClient.get().postService()

	   // for internal usage
	   private val _posts = MutableLiveData<ResultOf<Post>>()

	   // Expose to the outside world
	   val posts: LiveData<ResultOf<Post>> = _posts

	   @UiThread
	   fun fetchPostsFromApi() {
	      viewModelScope.launch(Dispatchers.IO) {
	          try {
	             val response = postService.getAllPosts()
	             _posts.postValue(ResultOf.Success(response.data)) 
	          } catch (ioe: IOException) {
	            _posts.postValue(ResultOf.Failure("[IO] error please retry", ioe)) 
	          } catch (he: HttpException) { 
	            _posts.postValue(ResultOf.Failure("[HTTP] error please retry", he)) 
	          }
	      }
	   }

	}

After this, we can finally observe it from our Activities or Fragments.

/* Copyright 2020 Seanghay Yath (@seanghay)
	   SPDX-License-Identifier: Apache-2.0 */

	class PostListFragment: Fragment() {

	   // `viewModels` is a extension from fragment-ktx
	   private val viewModel: PostViewModel by viewModels()

	   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
	     // just a normal ListAdapter of RecyclerView 
	     val adapter = PostListAdapter() 

	     // set our adapter to the view
	     binding.recyclerView.adapter = adapter

	     // observe result from the ViewModel
	     viewModel.observe(viewLifecycleOwner, Observer { result ->
	        when (result) {
	          // there is no need for type-casting, the compiler already knows that
	          is ResultOf.Success -> {
	             adapter.submitList(result.value)
	          }
	          // here as well
	          is ResultOf.Failure -> {
	             showErrorMessage(result.message ?: "Unknown error message")
	          }
	        }
	     })

	     viewModel.fetchPostsFromApi()
	   }

	}

Look through, these sample codes, we might be thinking it’s the best way to work with, but there is more we can do to improve it by using Kotlin extension functions.

#sealed-classes #kotlin #android #java

What is GEEK

Buddha Community

Kotlin sealed class for success and error handling
Lawrence  Lesch

Lawrence Lesch

1662107520

Superdom: Better and Simpler ES6 DOM Manipulation

Superdom

You have dom. It has all the DOM virtually within it. Use that power:

// Fetch all the page links
let links = dom.a.href;

// Links open in a new tab
dom.a.target = '_blank';

Only for modern browsers

Getting started

Simply use the CDN via unpkg.com:

<script src="https://unpkg.com/superdom@1"></script>

Or use npm or bower:

npm|bower install superdom --save

Select

It always returns an array with the matched elements. Get all the elements that match the selector:

// Simple element selector into an array
let allLinks = dom.a;

// Loop straight on the selection
dom.a.forEach(link => { ... });

// Combined selector
let importantLinks = dom['a.important'];

There are also some predetermined elements, such as id, class and attr:

// Select HTML Elements by id:
let main = dom.id.main;

// by class:
let buttons = dom.class.button;

// or by attribute:
let targeted = dom.attr.target;
let targeted = dom.attr['target="_blank"'];

Generate

Use it as a function or a tagged template literal to generate DOM fragments:

// Not a typo; tagged template literals
let link = dom`<a href="https://google.com/">Google</a>`;

// It is the same as
let link = dom('<a href="https://google.com/">Google</a>');

Delete elements

Delete a piece of the DOM

// Delete all of the elements with the class .google
delete dom.class.google;   // Is this an ad-block rule?

Attributes

You can easily manipulate attributes right from the dom node. There are some aliases that share the syntax of the attributes such as html and text (aliases for innerHTML and textContent). There are others that travel through the dom such as parent (alias for parentNode) and children. Finally, class behaves differently as explained below.

Get attributes

The fetching will always return an array with the element for each of the matched nodes (or undefined if not there):

// Retrieve all the urls from the page
let urls = dom.a.href;     // #attr-list
  // ['https://google.com', 'https://facebook.com/', ...]

// Get an array of the h2 contents (alias of innerHTML)
let h2s = dom.h2.html;     // #attr-alias
  // ['Level 2 header', 'Another level 2 header', ...]

// Get whether any of the attributes has the value "_blank"
let hasBlank = dom.class.cta.target._blank;    // #attr-value
  // true/false

You also use these:

  • html (alias of innerHTML): retrieve a list of the htmls
  • text (alias of textContent): retrieve a list of the htmls
  • parent (alias of parentNode): travel up one level
  • children: travel down one level

Set attributes

// Set target="_blank" to all links
dom.a.target = '_blank';     // #attr-set
dom.class.tableofcontents.html = `
  <ul class="tableofcontents">
    ${dom.h2.map(h2 => `
      <li>
        <a href="#${h2.id}">
          ${h2.innerHTML}
        </a>
      </li>
    `).join('')}
  </ul>
`;

Remove an attribute

To delete an attribute use the delete keyword:

// Remove all urls from the page
delete dom.a.href;

// Remove all ids
delete dom.a.id;

Classes

It provides an easy way to manipulate the classes.

Get classes

To retrieve whether a particular class is present or not:

// Get an array with true/false for a single class
let isTest = dom.a.class.test;     // #class-one

For a general method to retrieve all classes you can do:

// Get a list of the classes of each matched element
let arrays = dom.a.class;     // #class-arrays
  // [['important'], ['button', 'cta'], ...]

// If you want a plain list with all of the classes:
let flatten = dom.a.class._flat;     // #class-flat
  // ['important', 'button', 'cta', ...]

// And if you just want an string with space-separated classes:
let text = dom.a.class._text;     // #class-text
  // 'important button cta ...'

Add a class

// Add the class 'test' (different ways)
dom.a.class.test = true;    // #class-make-true
dom.a.class = 'test';       // #class-push

Remove a class

// Remove the class 'test'
dom.a.class.test = false;    // #class-make-false

Manipulate

Did we say it returns a simple array?

dom.a.forEach(link => link.innerHTML = 'I am a link');

But what an interesting array it is; indeed we are also proxy'ing it so you can manipulate its sub-elements straight from the selector:

// Replace all of the link's html with 'I am a link'
dom.a.html = 'I am a link';

Of course we might want to manipulate them dynamically depending on the current value. Just pass it a function:

// Append ' ^_^' to all of the links in the page
dom.a.html = html => html + ' ^_^';

// Same as this:
dom.a.forEach(link => link.innerHTML = link.innerHTML + ' ^_^');

Note: this won't work dom.a.html += ' ^_^'; for more than 1 match (for reasons)

Or get into genetics to manipulate the attributes:

dom.a.attr.target = '_blank';

// Only to external sites:
let isOwnPage = el => /^https?\:\/\/mypage\.com/.test(el.getAttribute('href'));
dom.a.attr.target = (prev, i, element) => isOwnPage(element) ? '' : '_blank';

Events

You can also handle and trigger events:

// Handle click events for all <a>
dom.a.on.click = e => ...;

// Trigger click event for all <a>
dom.a.trigger.click;

Testing

We are using Jest as a Grunt task for testing. Install Jest and run in the terminal:

grunt watch

Download Details:

Author: franciscop
Source Code: https://github.com/franciscop/superdom 
License: MIT license

#javascript #es6 #dom 

Einar  Hintz

Einar Hintz

1593396615

Kotlin sealed class for success and error handling

A well-known Use-case

Sealed class is not new in other programming languages such as C# and Scala. The sealed class provides a way to organize our code to look a lot nicer and easy to work with.

/* Copyright 2020 Seanghay Yath.	
	   SPDX-License-Identifier: Apache-2.0 */

	@WorkerThread
	suspend fun fetchPosts() {
	  val response = httpClient.posts()

	  withContext(Dispatchers.Main) {
	    when (response) {
	      is ResultOf.Success -> {
	        // destructing data object
	        val (posts) = response

	        // update the view
	        adapter.submitList(posts)
	      } 

	      is ResultOf.Failure -> {
	        val (message, throwable) = response;
	        handlePostsFailure(messsage, throwable)

	        // log error message to logcat
	        Timber.e(throwable, message)
	      }
	    }
	  }
	}

An example of how to use Sealed class for handling error and success

As you can see in the example above that there is no need to manually cast objects. Kotlin compiler knows what data type it should be.

Sealed classes work well with LiveData and ViewModels

Oftentimes, we use LiveData to store data from APIs or databases, however, data from those I/O operations could cause failure, so the best way to handle those errors and successful responses is to use Sealed classes.

/* Copyright 2020 Seanghay Yath (@seanghay)
	   SPDX-License-Identifier: Apache-2.0 */

	sealed class ResultOf<out T> {
	  data class Success<out R>(val value: R): ResultOf<R>()
	  data class Failure(
	     val message: String?, 
	     val throwable: Throwable?
	  ): ResultOf<Nothing>()
	}

In our ViewModels, it would look something similar to this. I assume that you all familiar with Kotlin Coroutines.

/* Copyright 2020 Seanghay Yath (@seanghay)
	   SPDX-License-Identifier: Apache-2.0 */

	class PostViewModel: ViewModel() {

	   // Retrofit service
	   private val postService: PostService = HttpClient.get().postService()

	   // for internal usage
	   private val _posts = MutableLiveData<ResultOf<Post>>()

	   // Expose to the outside world
	   val posts: LiveData<ResultOf<Post>> = _posts

	   @UiThread
	   fun fetchPostsFromApi() {
	      viewModelScope.launch(Dispatchers.IO) {
	          try {
	             val response = postService.getAllPosts()
	             _posts.postValue(ResultOf.Success(response.data)) 
	          } catch (ioe: IOException) {
	            _posts.postValue(ResultOf.Failure("[IO] error please retry", ioe)) 
	          } catch (he: HttpException) { 
	            _posts.postValue(ResultOf.Failure("[HTTP] error please retry", he)) 
	          }
	      }
	   }

	}

After this, we can finally observe it from our Activities or Fragments.

/* Copyright 2020 Seanghay Yath (@seanghay)
	   SPDX-License-Identifier: Apache-2.0 */

	class PostListFragment: Fragment() {

	   // `viewModels` is a extension from fragment-ktx
	   private val viewModel: PostViewModel by viewModels()

	   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
	     // just a normal ListAdapter of RecyclerView 
	     val adapter = PostListAdapter() 

	     // set our adapter to the view
	     binding.recyclerView.adapter = adapter

	     // observe result from the ViewModel
	     viewModel.observe(viewLifecycleOwner, Observer { result ->
	        when (result) {
	          // there is no need for type-casting, the compiler already knows that
	          is ResultOf.Success -> {
	             adapter.submitList(result.value)
	          }
	          // here as well
	          is ResultOf.Failure -> {
	             showErrorMessage(result.message ?: "Unknown error message")
	          }
	        }
	     })

	     viewModel.fetchPostsFromApi()
	   }

	}

Look through, these sample codes, we might be thinking it’s the best way to work with, but there is more we can do to improve it by using Kotlin extension functions.

#sealed-classes #kotlin #android #java

Juned Ghanchi

1621508255

Kotlin App Development Company in India, Hire Kotlin Developers

We are a prime Kotlin app developer in India. We build and provide the best personalized Android apps, migration services, ongoing maintenance, and management.

We have the most efficient Kotlin developers that build ultramodern, interactive, and secure mobile apps. The technologies we use to create the most advanced Kotlin apps are AR/VR, AI/ML, IoT, etc.

Hire Kotlin app developers in India. Meet us, and we will help you meet all of your technology requirements.

#kotlin app development company india #hire kotlin developers india #kotlin app development company #hire kotlin developers #kotlin development agency #kotlin app programmers

Yashi Tyagi

1617449307

CA Classes - Best CA Classes Online

Chartered Accountancy course requires mental focus & discipline, coaching for CA Foundation, CA Inter and CA Finals are omnipresent, and some of the best faculty’s classes have moved online, in this blog, we are going to give the best way to find online videos lectures, various online websites provide the CA lectures, Smartnstudy one of the best site to CA preparation, here all faculty’s video lecture available.

check here : ca classes

#ca classes online #ca classes in delhi #ca classes app #ca pendrive classes #ca google drive classes #best ca classes online

Target Class Does Not Exist In Laravel 8

As you all know laravel 8 already released and you can see there are many changes and update in laravel 8 version. many laravel users are facing issue in their new Laravel 8 version when they try to load their routes in web.php and they run into an Exception that says something like “Target class postController does not exist”.

Target Class Does Not Exist In Laravel 8

https://websolutionstuff.com/post/target-class-does-not-exist-in-laravel-8

#target class does not exist in laravel 8 #error #target class controller does not exist #target class not found #laravel #target class does not exist error solved